/**
 * bootstrapTable 的insertRow方法传给field为index属性的变量
 */
var billIndex = 1;//提运单列表序号
var contaIndex = 1;//集装箱列表序号
var commodityIndex = 1;//商品
var chgIndex = 1;//变更原因
var consigneeIndex = 1;//收货人
var consigneeContactIndex = 1;//收货具体联系人
var consignorIndex = 1;//发货人
var notifyIndex = 1;//通知人
var undgIndex = 1;//危险品联系人

/**
 * 更新方法执行时传入的行所在的位置，数值是行所在的位置（不是行的序号，也不是行的index而是行的位置，位置从0开始，所以第3行的位置即为2）
 */

var updateGoodsIndex = -1;
var updateContainerIndex = -1;
var updateChgIndex = -1;//变更原因更新行号
var updateConsigneeIndex = -1;//收货人需要更新的行号
var updateconsigneeContactIndex = -1;//收货具体联系人更新行号
var updateConsignorIndex = -1;//发货人更新行的位置
var updateNotifyIndex = -1;//通知人更新行的位置
var updateUndgIndex = -1;//危险品联系人需要更新的行的位置

/**
 * 是否执行更新方法的标记
 */
var billSaveFlag = false;
var billChangeFlag = false;
var containerFlag = false;
var goodsInfoFlag = false;
var chgFlag = false;//变更原因执行更新方法标记
var consigneeFlag = false;//收货人执行更新方法标记
var updateconsigneeContactIndexFlag = false;//收货具体联系人执行更新方法标记
var consignorFlag = false;//发货人执行更新方法标记
var notifyFlag = false;//通知人执行更新方法标记
var undgFlag = false;//危险品联系人执行更新方法标记
/***************************预配舱单信息***********************/
/**获取公共表头对象**/
function getHead(){
    var messageType='MT2401';
    var unitCode=$("#unitCode").val();
    if(unitCode.length===18){
        unitCode=unitCode.substr(8,9);//截取9到17位的字符串
    }
    var senderID=$("#customMaster").val()+unitCode+"_0000000000";
    var sender=$("#customMaster").val()+unitCode;

    var sendTime=getDateAndTime();
    var messageID = 'CN_' + messageType + '_1p0_' + sender + '_' + sendTime;
    var receiverID='EPORT';
    var version='1.0';
    var functionCode='';
    if(pageType=="main"){
        functionCode = '9';
    }else if(pageType=="change"){
        functionCode = '5';
    }else if(pageType=="delete"){
        functionCode = '3';
    }
    //报文头结束
    //二级标签开始
    var head = {
        "messageID": messageID,
        "functionCode": functionCode,
        "messageType": messageType,
        "senderID": senderID,
        "receiverID": receiverID,
        "sendTime": sendTime,
        "version": version
    };
    return head;
}
//获取页面信息公共方法  getAllSaveInfo  getAllInfo
var isSaveOrDeclaration = false;//判断是暂存还是申报的标记 false是暂存 true是申报(暂存是默认全选，申报是只取选中的数据）
function getAllInfo(){


    //-------------------
    //表头表单序列化
    var headData=$("#org_mtf_m_head_form").serializeJson();

    //------------------declaration子标签-------------------
    //consignment数组
    var consignments=new Array();
    var consignmentTables=null;
    if(isSaveOrDeclaration){
        consignmentTables=$("#billOfLadingInformationTalbe").bootstrapTable("getSelections");
    }else{
        consignmentTables=$("#billOfLadingInformationTalbe").bootstrapTable("getData");
    }
    for(var i=0;i<consignmentTables.length;i++){

        var consignmentTable = {
            "grossVolumeMeasure": {
                "value": consignmentTables[i].cube,//货物体积
                "unitCode": "MTQ"
            },
            "totalPackageQuantity": {
                "unitCode": consignmentTables[i].packTypeCode,//包装种类
                "value": consignmentTables[i].packNum//货物总件数
            },
            "valueAmount": {
                "currencyID": consignmentTables[i].currencyTypeCode,//金额类型
                "value": consignmentTables[i].goodsValue//货物价值
            },
//			        "borderTransportMeans": {
//			        	"itinerary":{"routingCountryCode":consignmentTables[i].routingContrys}//途径国家代码
////
//			        },
            "consignee": {
                "id": consignmentTables[i].consigneeId,//收货人代码
                "name": consignmentTables[i].consigneeName,//收货人名称
                "communication": consignmentTables[i].communicationConsignee,//收货人联系方式
                "contact": {
                    "name": consignmentTables[i].consigneeContactName,//收货具体联系人名称
                    "communication": consignmentTables[i].communicationContact//收货具体联系人联系方式
                }
            },
            "consignmentItem": consignmentTables[i].consignmentItems,//商品项数组
            "consignor": {
                "id": consignmentTables[i].consignorId,//发货人代码
                "name": consignmentTables[i].consignorName,//发货人名称
                "communication":consignmentTables[i].communicationConsignor//发货人联系方式
            },
            "freight": { "paymentMethodCode": consignmentTables[i].paymentTypeCode },//运费支付方法
            "governmentAgencyGoodsItem": {
                "goodsMeasure": {
                    "grossMassMeasure": {
                        "unitCode": "KGM",
                        "value": consignmentTables[i].grossWt//货物总毛重(KG)
                    }
                }
            },
            "governmentProcedure": { "currentCode": consignmentTables[i].goodsCustomsStatCode },//海关货物通关代码
            "notifyParty": {
                "id": consignmentTables[i].notifyId,//通知人id
                "name": consignmentTables[i].notifyName,//通知人名称
                "address": { "line": consignmentTables[i].notifyAddr },//通知人地址
                "communication":consignmentTables[i].communicationNotify //通知人联系方式
            },
            "transitDeparture": { "id":consignmentTables[i].transLocationIdCode  },//跨境启运地
            "transportContractDocument": {//提运单（合同）数据段
                "conditionCode": consignmentTables[i].conditionCode,//运输条款
                "id": consignmentTables[i].billNo,//提运单号
                "consolidator": { "id": consignmentTables[i].consolidatorId }//拼箱人代码
            },
            "transportEquipment": consignmentTables[i].transportEquipments,//集装箱数组
            "undgcontact": {
                "name": consignmentTables[i].undgContactName,//危险品联系人名称
                "communication": consignmentTables[i].communicationUndgContact//危险品联系人联系方式
            }
        };

        consignments.push(consignmentTable);
    }

    var additionalInformation={ "content": headData.additionalInformation

    };//备注
    var agent={ "id": headData.transAgentCode };//运输工具代理企业代码
    var borderTransportMeans={ "typeCode": headData.trafModeCode };//运输方式代码
    var carrier={ "id": headData.carrierCode };//承运人代码
    var loadingLocation={//装货地信息
        "id": headData.loadingLocationCode,
        "loadingDateTime": headData.loadingDate//货物装载时间
    };

    var representativePerson={ "name": headData.msgRepName };//舱单传输人名称
//	var unloadingLocation={
//	    "arrivalDateTime": "",//到达卸货地日期
//	    "id": ""//卸货地代码
//	  };
    //二级标签开始

    var declaration={
        "declarationOfficeID": headData.customsCode,//进出境口岸海关代码
        "id": headData.voyageNo,//货物运输批次号
        "additionalInformation": additionalInformation,//备注
        "agent": agent,
        "borderTransportMeans": borderTransportMeans,
        "carrier": carrier,
        "consignment":consignments,
        "loadingLocation":loadingLocation ,
        "representativePerson":representativePerson,
        "dataExchangeFlag":headData.dataExchangeId//中蒙数据交换项
//		      "unloadingLocation": unloadingLocation
    };
    return declaration;
}

function ExcelInfoFunc(){
    layer.open({
        type : 1,
        shadeClose : true,
        area : [ '480px', '325px' ],
        title : "提单导入",
        shade : 0.5,
        scrollbar : false,
        btn : [],// 按钮名称
        btnAlign : 'c', // 居中
        yes : function(index) {
            layer.close(index);
        },
        cancel : function() {
            $("#BillFileName").val("");
            $("#id_importBillDataForm_file").val("");
            queryHead();//查询方法
        },
        content : $("#importBillExcel")
    });
}

function ExcelgoodsfoFunc(){
    layer.open({
        type : 1,
        shadeClose : true,
        area : [ '480px', '325px' ],
        title : "商品项导入",
        shade : 0.5,
        scrollbar : false,
        btn : [],// 按钮名称
        btnAlign : 'c', // 居中
        yes : function(index) {
            layer.close(index);
        },
        cancel : function() {
            $("#BillFileName").val("");
            $("#id_importBillDataForm_file").val("");
            queryHead();//查询方法
        },
        content : $("#importgoodsExcel")
    });
}

function ExcelcontasfoFunc(){
    layer.open({
        type : 1,
        shadeClose : true,
        area : [ '480px', '325px' ],
        title : "集装箱项导入",
        shade : 0.5,
        scrollbar : false,
        btn : [],// 按钮名称
        btnAlign : 'c', // 居中
        yes : function(index) {
            layer.close(index);
        },
        cancel : function() {
            $("#BillFileName").val("");
            $("#id_importBillDataForm_file").val("");
            queryHead();//查询方法
        },
        content : $("#importcontasExcel")
    });
}
function fileSelect(formId){
    var value = $("#"+formId+"_file").val();
    if(value.length<1){
        $("#" + formId + " input[name='fileName']").val("请选择要上传的文件！");
        return false;
    }
    var fileName = value.split('\\').pop();
    $("#" + formId + " input[name='fileName']").val(fileName);
}

function excelDownload(dataType){
    var urlStr;
    if(dataType=='goods'){
        urlStr = BasePath + "/manifest/excel/download?datype=goods"
    }else if(dataType=='contas'){
        urlStr = BasePath + "/manifest/excel/download?datype=contas"
    }else{
        urlStr = BasePath+"/manifest/excel/download"
    }
    window.location.href = urlStr;
}
/**
 * Excel 导入
 */

function doUpload(formId,dataType){
    var uploadUrl;
    var queryDataList;

    if(dataType == 'goods'){
        uploadUrl = BasePath + "/manifest/excel/upload?busniessType=1&dataType=goods";
    }else if(dataType=="contas") {
        uploadUrl = BasePath + "/manifest/excel/upload?busniessType=1&dataType=contas";
    }else{
        uploadUrl = BasePath + "/manifest/excel/upload?busniessType=1&dataType=bills";
    }


    var value = $("#" + formId + "_file").val();
    if (!value) {
        layer.open({
            title : '提示',
            content : "请先选择要导入的文件！"
        });
        return false;
    }
    if (!value.match(/.xls|.XLS|.xlxs|.XLXS/i)) {
        layer.open({
            title : '提示',
            content : "导入格式错误，请导入xls/xlsx格式文件！"
        });
        return false;
    }

    var delTmpIndex = layer.load(1, {
        shade : [ 0.1, '#fff' ]
        //0.1透明度的白色背景
    });
    /*	var tallyNo =$("#tallyNo").val()
        var mftSeqNo = $("#mftSeqNo").val();
        var listNo = $("#listNo").val();*/
    var voyageNo = $("#voyageNo").val();
    var unitCode = $("#unitCode").val();

    /*var shipId = $("#shipId").val();*/
    var param = {
        voyageNo:voyageNo,
        unitCode:unitCode,
    }
    uploadUrl = uploadUrl+"&voyageNo="+voyageNo+"&unitCode="+unitCode
    var option = {
        url : uploadUrl,
        timeout : 120000,
        type : 'POST',
        dataType : 'json',
        data: JSON.stringify(param),
        contentType : false,
        headers : {
            "ClientCallMode" : "ajax"
        }, // 添加请求头部
        success : function(data){
            if(data.ok){
                layer.close(delTmpIndex);
                layer.msg('导入数据成功', {
                    icon : 1,
                    // 成功图标
                    time : 3000
                    // 2秒关闭（如果不配置，默认是3秒）
                });
            }else{
                layer.close(delTmpIndex);
                layer.alert(""+data.errors, {
                    // 失败图标
                    icon : 2,
                    title : "温馨提示"
                });
            }
        },
        error : function(jqXHR, status, error) {
            layer.close(delTmpIndex);
            ajaxErrorAlert(jqXHR, status, error);
        }
    }
    $("#" + formId).ajaxSubmit(option);
    return false; // 最好返回false，因为如果按钮类型是submit,则表单自己又会提交一次;返回false阻止表单再次提交
}
/**
 * 删除申请时的报文，比预配舱单报文少了部分节点
 */
function getDeleteInfo(){


    //-------------------
//表头表单序列化
    var headData=$("#org_mtf_m_head_form").serializeJson();

//------------------declaration子标签-------------------
//consignment数组
    var consignments=new Array();
    var consignmentTables=$("#billOfLadingInformationTalbe").bootstrapTable("getSelections");

    for(var i=0;i<consignmentTables.length;i++){
        var consignmentTable = {
            "transportContractDocument": {//提运单（合同）数据段
                "id": consignmentTables[i].billNo,//提运单号
                "amendment":{
                    "changeReasonCode": consignmentTables[i].chgCodeNames,
                    //1205 谢霖志 新增变更需求
                    "changeInformation":{
                        "reason":consignmentTables[i].reason,
                        "contact":consignmentTables[i].contact,
                        "phone":consignmentTables[i].phone
                    }
                    //1205 谢霖志 新增变更需求
                }//更改原因代码
            }
        };

        consignments.push(consignmentTable);
    }

    var additionalInformation={ "content": headData.additionalInformation };//备注
    var borderTransportMeans={ "typeCode": headData.trafModeCode };//运输方式代码

    var representativePerson={ "name": headData.msgRepName };//舱单传输人名称
//二级标签开始

    var declaration={
        "declarationOfficeID": headData.customsCode,//进出境口岸海关代码
        "id": headData.voyageNo,//货物运输批次号
        "additionalInformation": additionalInformation,//备注
        "borderTransportMeans": borderTransportMeans,
        "consignment":consignments,
        "representativePerson":representativePerson ,
    };
    return declaration;
}
/**
 * 变更申请时的报文，比预配舱单报文少了部分节点
 */
function getChangeInfo(){


    //-------------------
//表头表单序列化
    var headData=$("#org_mtf_m_head_form").serializeJson();

//------------------declaration子标签-------------------
//consignment数组
    var consignments=new Array();
    var consignmentTables=$("#billOfLadingInformationTalbe").bootstrapTable("getSelections");

    for(var i=0;i<consignmentTables.length;i++){
        var consignmentTable = {

            "grossVolumeMeasure": {
                "value": consignmentTables[i].cube,//货物体积
                "unitCode": "MTQ"
            },
            "totalPackageQuantity": {
                "unitCode": consignmentTables[i].packTypeCode,//包装种类
                "value": consignmentTables[i].packNum//货物总件数
            },
            "valueAmount": {
                "currencyID": consignmentTables[i].currencyTypeCode,//金额类型
                "value": consignmentTables[i].goodsValue//货物价值
            },
            "consignee": {
                "id": consignmentTables[i].consigneeId,//收货人代码
                "name": consignmentTables[i].consigneeName,//收货人名称
                "communication": consignmentTables[i].communicationConsignee,//收货人联系方式
                "contact": {
                    "name": consignmentTables[i].consigneeContactName,//收货具体联系人名称
                    "communication": consignmentTables[i].communicationContact//收货具体联系人联系方式
                }
            },
            "consignmentItem": consignmentTables[i].consignmentItems,//商品项数组
            "consignor": {
                "id": consignmentTables[i].consignorId,//发货人代码
                "name": consignmentTables[i].consignorName,//发货人名称
                "communication":consignmentTables[i].communicationConsignor//发货人联系方式
            },
            "freight": { "paymentMethodCode": consignmentTables[i].paymentTypeCode },//运费支付方法
            "governmentAgencyGoodsItem": {
                "goodsMeasure": {
                    "grossMassMeasure": {
                        "unitCode": "KGM",
                        "value": consignmentTables[i].grossWt//货物总毛重(KG)
                    }
                }
            },
            //"governmentProcedure": { "currentCode": consignmentTables[i].goodsCustomsStatCode }, //海关货物通关代码
            "notifyParty": {
                "id": consignmentTables[i].notifyId,//通知人id
                "name": consignmentTables[i].notifyName,//通知人名称
                "address": { "line": consignmentTables[i].notifyAddr },//通知人地址
                "communication":consignmentTables[i].communicationNotify //通知人联系方式
            },
            "transportContractDocument": {//提运单（合同）数据段
                "conditionCode": consignmentTables[i].conditionCode,//运输条款
                "id": consignmentTables[i].billNo,//提运单号
                "amendment":{
                    "changeReasonCode": consignmentTables[i].chgCodeNames,
                    //1205 谢霖志 新增无纸化变更需求
                    "changeInformation":{
                        "reason":consignmentTables[i].reason,
                        "phone":consignmentTables[i].phone,
                        "contact":consignmentTables[i].contact
                    },
                    //1205
                },//更改原因代码
                "consolidator": { "id": consignmentTables[i].consolidatorId },//拼箱人代码
            },
            "undgcontact": {
                "name": consignmentTables[i].undgContactName,//危险品联系人名称
                "communication": consignmentTables[i].communicationUndgContact//危险品联系人联系方式
            }
        };

        consignments.push(consignmentTable);
    }

    var additionalInformation={ "content": headData.additionalInformation

    };//备注
    var borderTransportMeans={ "typeCode": headData.trafModeCode };//运输方式代码

    var representativePerson={ "name": headData.msgRepName };//舱单传输人名称
//二级标签开始

    var declaration={
        "declarationOfficeID": headData.customsCode,//进出境口岸海关代码
        "id": headData.voyageNo,//货物运输批次号
        "additionalInformation": additionalInformation,//备注
        "borderTransportMeans": borderTransportMeans,
        "consignment":consignments,
        "representativePerson":representativePerson ,
        "dataExchangeFlag":headData.dataExchangeId//中蒙数据交换项
    };
    return declaration;
}

/**
 * 预配舱单主要数据表头信息暂存方法
 */
function saveMftHeadFunc() {
    // 字段校验

    /*if (!$("#org_mtf_m_head_form").valid()) {
        layer.open({
            title : '提示信息',
            content : '必填项未填写!',
            time : 3000
        // 2秒关闭（如果不配置，默认是3秒）
        });
        return;
    }*/
    //表头非空校验
    if(headInfoNotNull()){
        return;
    }


    var flag = false;
    //判断提运单号是否重复
    var billInfos=$("#billOfLadingInformationTalbe").bootstrapTable("getData");
    var contaRepeatFlag = isContaIdRepeat(billInfos);//判断集装箱编号是否重复
    if(contaRepeatFlag){
        return;
    }
    //var billInfoFlag = false;
    var repeatCode;
    if(billInfos.length>1){
        var i = null;
        var j = null;
        for( i = 0; i < billInfos.length - 1; i++){
            var billInfoI = billInfos[i].billNo;
            for( j = i+1; j < billInfos.length ; j++){
                var billInfoJ = billInfos[j].billNo;
                if(billInfoI==billInfoJ){
                    repeatCode=billInfoI;
                    flag = true;
                    break;
                }
            }
        }
    }
    if(flag){
        showLayerWarnMsg("提（运）单号"+repeatCode+"重复");
        return;
    }
    /*var billInputs = [];
    billInputs.push(
            'billNo', 'paymentType',
            'goodsCustomsStat', 'packNum', 'packType',
            'grossWt', 'goodsValue', 'currencyType',

            'contaId',
            'goodsPackNum', 'goodsPackType',
            'goodsGrossWt', 'goodsBriefDesc', 'undgNoName',
            'goodsDetailDesc',
            'currencyType',
            'consigneeName',
            'consignorName'
            );
    $("input").each(function() {
        if (($.inArray($(this)[0].id, billInputs) >= 0)) {
            if($(this).val()==''){

                flag = true;
                return;
            }
        }
    });
    if(flag){
        showLayerWarnMsg("有未填写的必填项", 3000);
        return;
    }*/
    // 实例化表单数据并将其转换为json格式
    var serviceName='eport.superpass.roadmft.CommonManifestSaveService';
    var head=getHead();
    head.functionCode="T";
    /*//报文头开始
    var messageID='CN_MT2401_1p0_1111111111111_20130914142747515';
    var functionCode='T';
    var messageType='MT2401';
    //var senderID=$("#customMasterName").val()+$("#unitCode").val();
    var senderID=$("#customMaster").val()+$("#unitCode").val()+'_0400620001';
    var receiverID='EPORT';
    var sendTime='20111115155146555';
    var version='1.0';
    //报文头结束
    //二级标签开始
     var head = {
              "messageID": messageID,
              "functionCode": functionCode,
              "messageType": messageType,
              "senderID": senderID,
              "receiverID": receiverID,
              "sendTime": sendTime,
              "version": version
            };*/
    isSaveOrDeclaration = false;
    var declaration=getAllInfo();
    //二级标签结束
    //-----------------------------------------------------------------
    var manifestVo={
        "serviceName":serviceName,
        "manifest":{
            "head": head,
            "declaration": declaration
        }
    };

    var saveMftHeadIndex = layer.load(1, {
        shade : [ 0.1, '#fff' ]
        // 0.1透明度的白色背景
    });
    $.ajax({
        type : "POST",
        url : BasePath+"/advanceManifest/save?msgType="+ msgType,
        data : JSON.stringify(manifestVo),
        contentType : "application/json;charset=utf-8",
        dataType : "json",
        success : function(json) {
            layer.close(saveMftHeadIndex);
            if(json.ok){
                //暂存成功后激活按钮
                $("#mft_declare").attr("disabled", false);//申报
                $("#mft_copy").attr("disabled", false);//申报按钮
                $("#delete_mft_head").attr("disabled", false);//删除
                $("#voyageNo").attr("readonly",true);
                $("#sysRand").attr("disabled", false);
                $("#billNo").focus();
                showLayerMsg("暂存成功!", 3000);
            }else{
                var msg=json.data.msg;
                showLayerFailMsg(msg);
            }
        },
        complete:function(){
            layer.close(saveMftHeadIndex);
        }
    });

};
/**
 * 申报
 */
function decMainData(options){
    // 字段校验
    if (!$("#org_mtf_m_head_form").valid()) {
        return;
    };

    var datas=$("#billOfLadingInformationTalbe").bootstrapTable("getData");
    var sel=$("#billOfLadingInformationTalbe").bootstrapTable("getSelections");
    if(datas.length==0){
        showLayerWarnMsg("请至少添加一条表体记录",null);
        return;
    }else if(sel.length==0){
        showLayerWarnMsg("请至少选择一条表体记录",null);
        return;
    }
    var contaRepeatFlag = isContaIdRepeat(sel);//判断集装箱编号是否重复
    if(contaRepeatFlag){
        return;
    }
    var changeResonFlag = false;
    for(var i=0;i<sel.length;i++){
        var changeReson = sel[i].chgCodeNames;
        var consigneeName = sel[i].consigneeName;
        var consignorName = sel[i].consignorName;
        var goodsCustomsStatCode = sel[i].goodsCustomsStatCode;
        var grossWt = sel[i].grossWt;
        if(pageType=="main"){
            if(!isNotEmpty(consigneeName)){
                showLayerWarnMsg("收货人名称必填",null);
                changeResonFlag = true;
                break;
            }
            if(!isNotEmpty(consignorName)){
                showLayerWarnMsg("发货人名称必填",null);
                changeResonFlag = true;
                break;
            }
            if(!isNotEmpty(goodsCustomsStatCode)){
                showLayerWarnMsg("海关货物通关代码必填",null);
                changeResonFlag = true;
                break;
            }
            if(!isNotEmpty(grossWt)){
                showLayerWarnMsg("货物总毛重(KG)必填",null);
                changeResonFlag = true;
                break;
            }
        }
    }

    if(changeResonFlag) return;


    var head = getHead();
    isSaveOrDeclaration = true;
    var declaration = null;
    if(pageType=="main"){
        declaration=getAllInfo();
    }else if(pageType==="change"){
        declaration=getChangeInfo();

    }else{
        declaration=getDeleteInfo();
    }


    if(pageType==="change"||pageType==="delete"){
        var consignmentArr=declaration.consignment;
        var f=true;
        for(var i=0;i<consignmentArr.length;i++){
            var codeArr=consignmentArr[i].transportContractDocument.amendment.changeReasonCode;
            if(codeArr.length==0){
                f=false;
                break;
            }

        }
        if(!f){
            showLayerWarnMsg("变更原因不能为空");
            return;
        }
        if(changeInformationSwitch){
            for(var i=0;i<sel.length;i++){
                //1213 申报校验
                var reason = sel[i].reason;
                var contact = sel[i].contact;
                var phone = sel[i].phone;

                if(!isNotNull(reason)){
                    showLayerWarnMsg("提运单号："+sel[i].billNo+"变更原因描述应不为空！");
                    return;
                }
                if(!isNotNull(contact)){
                    showLayerWarnMsg("提运单号："+sel[i].billNo+"变更申请联系人姓名应不为空！");
                    return  ;
                }
                if(!isNotNull(phone)){
                    showLayerWarnMsg("提运单号："+sel[i].billNo+"变更申请联系人电话应不为空！");
                    return ;
                }
            }
        }else{
            for(var i=0;i<sel.length;i++){
                //1213 申报校验
                var reason = sel[i].reason;
                var contact = sel[i].contact;
                var phone = sel[i].phone;

                var count = new Array();
                if(isNotNull(reason)){
                    count.push(reason)
                }
                if(isNotNull(contact)){
                    count.push(contact)
                }
                if(isNotNull(phone)){
                    count.push(phone)
                }
                if(count.length > 0 && count.length < 3){
                    if(!isNotNull(reason)){
                        showLayerWarnMsg("提运单号："+sel[i].billNo+"变更原因描述应不为空！");
                        return;
                    }
                    if(!isNotNull(contact)){
                        showLayerWarnMsg("提运单号："+sel[i].billNo+"变更申请联系人姓名应不为空！");
                        return  ;
                    }
                    if(!isNotNull(phone)){
                        showLayerWarnMsg("提运单号："+sel[i].billNo+"变更申请联系人电话应不为空！");
                        return ;
                    }
                }
            }
        }

    }

    var flag=false;
    var billInfos=$("#billOfLadingInformationTalbe").bootstrapTable("getSelections");
    //var billInfoFlag = false;
    var repeatCode;
    if(billInfos.length>1){
        var i = null;
        var j = null;
        for( i = 0; i < billInfos.length - 1; i++){
            var billInfoI = billInfos[i].billNo;
            for( j = i+1; j < billInfos.length ; j++){
                var billInfoJ = billInfos[j].billNo;
                if(billInfoI==billInfoJ){
                    repeatCode=billInfoI;
                    flag = true;
                    break;
                }
            }
        }
    }
    if(flag){
        showLayerWarnMsg("提（运）单号"+repeatCode+"重复",null);
        return;
    }


    if(pageType==="main"){
        //商品项非空判断
        var consig = declaration.consignment;
        if(isNotEmpty(consig)){
            for(var i=0;i<consig.length;i++){
                if(consig[i].consignmentItem.length===0){
                    showLayerFailMsg("申报失败,商品项信息不能为空",null);
                    return ;
                }
            }
        }
    }


    var serviceName="eport.superpass.roadmft.common.ClientMsgDeclareService";
    var manifestVo={
        "serviceName":serviceName,
        "manifest":{
            "head": head,
            "declaration": declaration
        }
    };

    var saveMftHeadIndex = layer.load(1, {
        shade : [ 0.1, '#fff' ]
        // 0.1透明度的白色背景
    });
    $.ajax({
        type : "POST",
        url : BasePath+"/advanceManifest/declare?msgType="+ msgType,
        data : JSON.stringify(manifestVo),
        contentType : "application/json;charset=utf-8",
        dataType : "json",
        success : function(json) {
            layer.close(saveMftHeadIndex);

            if(json.ok){
                $("#sysRand").attr("disabled", true);
                $("#org_head_save").attr("disabled", true);//暂存
                $("#mft_copy").attr("disabled", false);//暂存
                $("#delete_mft_head").attr("disabled", true);//删除
                layer.close(saveMftHeadIndex);
                showLayerMsg("申报成功",3000);
            }else{
                var msg=json.data.msg;
                showLayerFailMsg(msg,null);
            }

        },
        complete:function(){
            layer.close(saveMftHeadIndex);
        }

    });

}

function decCopyData(){
    $("#voyageNo").val("");
    $("#voyageNo").attr("readOnly",false);
    $("#sysRand").attr("disabled", false);
    $("#delete_mft_head").attr("disabled", true);
    $("#mft_declare").attr("disabled", true);
    $("#mft_copy").attr("disabled", true);
    $("#org_head_save").attr("disabled", false);
}
/**
 * 功能： 输入航班航次编号和运输工具代码后，在运输工具输入框上敲击回车键，如果数据库存在数据就反填到表提信息
 *
 */
function queryHead(option){
    // 实例化表单数据并将其转换为json格式
    var serviceName='eport.superpass.roadmft.CommonManifestQueryService';
    //报文头开始
//	var functionCode='9';
    var messageType='MT2401';
    var voyageNo=$("#voyageNo").val();
    var contaId=$("#contaId").val();
//	var mftId=option;
    //报文头结束

    /* var declaration=getAllInfo();*/
    //二级标签结束
    //-----------------------------------------------------------------
    var queryVo={
        "serviceName":serviceName,
        "queryRequest":{
            "queryCondition": {
                "mftId":option,
                "msgType":messageType,
                "voyageNo":voyageNo,
                "voyageNoNew":'',
                "shipId":'',
                "contaId":contaId,
                "referenceId":'',
                "unitCode":''
            }
        }
    };
    var saveMftHeadIndex = layer.load(1, {
        shade : [ 0.1, '#fff' ]
        // 0.1透明度的白色背景
    });
    $.ajax({
        type : "POST",
        url : BasePath+"/advanceManifest/query?msgType="+ msgType,
        data : JSON.stringify(queryVo),
        contentType : "application/json;charset=utf-8",
        dataType : "json",
        success : function(json) {
            layer.close(saveMftHeadIndex);
            if(!json.ok){
                var msg=(json.messageList)[0];
                $("#customsCodeName").focus();//没查询到数据光标定位到下个录入框
                /*showLayerWarnMsg(msg);*/
            }else{
                if(isNotNull(json.data) && isNotNull(json.data.resultObject)){
                    //清空列表和表单数据数据
                    $("#billOfLadingInformationTalbe").bootstrapTable("removeAll");
                    clearBillFormData();
                    var jsonData=json.data.resultObject;
                    //var jsonData = data.manifest;
                    layer.close(saveMftHeadIndex);
                    //变更申请查询到数据时几个列表数据数量不得改变（灰掉新增和删除按钮）

                    if(pageType=="change"||pageType=="delete"){
                        //$("#billOfLadingInformationAddBtn").attr("disabled", true);//提运单新增
                        $("#bill_add").attr("disabled", true);
                        $("#delete_mft_bill").attr("disabled", true);//提运单删除
                        $("#bill_info_copy").attr("disabled", true);//复制
                        $("#goodsTotal").attr("disabled", true);//汇总
                        $("#mft_container_save").attr("disabled", true);//集装箱新增
                        $("#container_add").attr("disabled", true);
                        $("#mft_container_delete").attr("disabled", true);//集装箱删除
                        $("#commodity_add").attr("disabled", true);//商品项新增
                        //$("#commodity_info_save").attr("disabled", true);//商品项保存
                        $("#mft_goods_delete").attr("disabled", true);//商品项删除
                        $("#billNo").attr("readonly",true);//提运单号
                        /*$("#goodsCustomsStat").attr("readonly",true);//海关货物通关
                        $("#packNum").attr("readonly",true);//货物总件数
                        $("#packType").attr("readonly",true);//包装种类代码
                        $("#grossWt").attr("readonly",true);//货物总毛重
    */					billChangeFlag = true;
                    }else if(pageType=="delete"){
                        $("#commodity_info_save").attr("disabled", true);//商品项新增
                    }

                    //若有反填数据，关键字置灰
                    $("#voyageNo").attr("readonly", "readonly");
                    $("#sysRand").attr("disabled", true);//系统分配批次
                    //按钮激活
                    if(jsonData.head.functionCode == "T"){
                        $("#org_head_save").attr("disabled", false);//暂存
                        $("#mft_copy").attr("disabled", false);//暂存
                        $("#mft_declare").attr("disabled", false);//申报
                        $("#delete_mft_head").attr("disabled", false);//删除
                    }else{
                        $("#mft_copy").attr("disabled", false);//暂存
                        $("#mft_declare").attr("disabled", false);//申报
                        $("#org_head_save").attr("disabled", true);//暂存
                    }

                    if(jsonData.head&&jsonData.declaration){
                        //表头表单对象
                        var headForm={};
                        if(isNotNull(jsonData.head)){
                            //						 if(isNotNull(jsonData.head.senderID)){
                            //	                        	headForm['customMaster']=jsonData.head.senderID.substr(0,4);//传输企业备案关区
                            //	                        	headForm['unitCode']=jsonData.head.senderID.substr(4);//组织机构代码
                            //	                         }

                        }
                        if (jsonData.declaration.id !== null && jsonData.declaration.id !== undefined && jsonData.declaration.id !== '') {
                            headForm['voyageNo']=jsonData.declaration.id;
                        };
                        /*if (jsonData.declaration.borderTransportMeans.typeCode !== null && jsonData.declaration.borderTransportMeans.typeCode !== undefined && jsonData.declaration.borderTransportMeans.typeCode !== '') {
                            headForm['trafModeCode']=jsonData.declaration.borderTransportMeans.typeCode;
                            };*/

                        if (jsonData.declaration.declarationOfficeID !== null && jsonData.declaration.declarationOfficeID !== undefined && jsonData.declaration.declarationOfficeID !== '') {
                            headForm['customsCode']=jsonData.declaration.declarationOfficeID;
                        };
                        if(isNotEmpty(jsonData.declaration.carrier)){
                            if (jsonData.declaration.carrier.id !== null && jsonData.declaration.carrier.id !== undefined && jsonData.declaration.carrier.id !== '') {
                                headForm['carrierCode']=jsonData.declaration.carrier.id;
                            };
                        }
                        if(isNotEmpty(jsonData.declaration.agent)){
                            if (jsonData.declaration.agent.id !== null && jsonData.declaration.agent.id !== undefined && jsonData.declaration.agent.id !== '') {
                                headForm['transAgentCode']=jsonData.declaration.agent.id;
                            };
                        }
                        if(isNotEmpty(jsonData.declaration.loadingLocation)){
                            if (jsonData.declaration.loadingLocation.loadingDateTime !== null && jsonData.declaration.loadingLocation.loadingDateTime !== undefined && jsonData.declaration.loadingLocation.loadingDateTime !== '') {
                                headForm['loadingDate']=jsonData.declaration.loadingLocation.loadingDateTime;//货物装载时间
                            };

                            if (jsonData.declaration.loadingLocation.id !== null && jsonData.declaration.loadingLocation.id !== undefined && jsonData.declaration.loadingLocation.id !== '') {
                                headForm['loadingLocationCode']=jsonData.declaration.loadingLocation.id;//卸货地代码
                            };
                        }




                        //					if (jsonData.declaration.unloadingLocation.arrivalDateTime !== null && jsonData.declaration.unloadingLocation.arrivalDateTime !== undefined && jsonData.declaration.unloadingLocation.arrivalDateTime !== '') {
                        //						headForm['arrivalDate']=jsonData.declaration.unloadingLocation.arrivalDateTime;//到达卸货地时间
                        //						};

                        /*if (jsonData.head.senderID !== null && jsonData.head.senderID !== undefined && jsonData.head.senderID !== '') {
                            headForm['customMaster']=jsonData.head.senderID.substring(0,4);
                            headForm['unitCode']=jsonData.head.senderID.substring(4);
                            };*/


                        if (jsonData.declaration.representativePerson.name !== null && jsonData.declaration.representativePerson.name !== undefined && jsonData.declaration.representativePerson.name !== '') {
                            headForm['msgRepName']=jsonData.declaration.representativePerson.name;
                        };


                        if (jsonData.declaration.additionalInformation.content !== null && jsonData.declaration.additionalInformation.content !== undefined && jsonData.declaration.additionalInformation.content !== '') {
                            headForm['additionalInformation']=jsonData.declaration.additionalInformation.content;
                        };
                        if (jsonData.declaration.dataExchangeFlag !== null && jsonData.declaration.dataExchangeFlag !== undefined && jsonData.declaration.dataExchangeFlag !== '') {
                            headForm['dataExchangeId']=jsonData.declaration.dataExchangeFlag;
                            if('MN'==jsonData.declaration.dataExchangeFlag){//参与中蒙数据交换标志
                                headForm['dataExchangeIdText'] = '参与中蒙数据交换';//显示框
                            }
                        };


                        //提运单表单对象
                        var billTables=new Array();
                        var bills=jsonData.declaration.consignment;
                        if (bills !== null && bills !== undefined && bills !== '') {

                            //console.log(bills);
                            for(var i=0;i<bills.length;i++){
                                var billTable={};

                                if(isNotEmpty(bills[i].transportContractDocument)){
                                    if (bills[i].transportContractDocument.id !== null && bills[i].transportContractDocument.id !== undefined && bills[i].transportContractDocument.id !== '') {
                                        billTable['billNo']=bills[i].transportContractDocument.id;//提运单号
                                    };

                                    if (bills[i].transportContractDocument.amendment.changeReasonCode !== null && bills[i].transportContractDocument.amendment.changeReasonCode !== undefined && bills[i].transportContractDocument.amendment.changeReasonCode !== '') {
                                        billTable['chgCodeNames']=bills[i].transportContractDocument.amendment.changeReasonCode;//更改原因数组
                                    };
                                    //1205 谢霖志 新增变更无纸化需求
                                    if(isNotEmpty(bills[i].transportContractDocument.amendment.changeInformation)){
                                        billTable['reason']=bills[i].transportContractDocument.amendment.changeInformation.reason;
                                        billTable['phone']=bills[i].transportContractDocument.amendment.changeInformation.phone;
                                        billTable['contact']=bills[i].transportContractDocument.amendment.changeInformation.contact;
                                    }
                                    //1205
                                    if (bills[i].transportContractDocument.conditionCode !== null && bills[i].transportContractDocument.conditionCode !== undefined && bills[i].transportContractDocument.conditionCode !== '') {
                                        billTable['conditionCode']=bills[i].transportContractDocument.conditionCode;//运输条款
                                    };
                                }

                                /*      if(isNotEmpty()){}   */


                                if(isNotEmpty(bills[i].freight)){
                                    if (bills[i].freight.paymentMethodCode !== null && bills[i].freight.paymentMethodCode !== undefined && bills[i].freight.paymentMethodCode !== '') {
                                        billTable['paymentTypeCode']=bills[i].freight.paymentMethodCode;//运费支付方法
                                    };
                                }
                                if(isNotEmpty(bills[i].governmentProcedure)){
                                    if (bills[i].governmentProcedure.currentCode !== null && bills[i].governmentProcedure.currentCode !== undefined && bills[i].governmentProcedure.currentCode !== '') {
                                        billTable['goodsCustomsStatCode']=bills[i].governmentProcedure.currentCode;//海关货物通关代码
                                        //
                                        if(isNotEmpty(bills[i].governmentProcedure.currentCode)){
                                            $('#goodsCustomsStat').autocomp2({// 隐藏框
                                                tableName:'CUS_MFT8_ROAD_CUSTOMS_STATUS',// 查询的同义词
                                                hiddenId:'goodsCustomsStatCode',// 显示框
                                                keyValue:bills[i].governmentProcedure.currentCode
                                            });
                                        }


                                        billTable['goodsCustomsStat']=$("#goodsCustomsStat").val();
                                        //console.log(billTable.goodsCustomsStat);
                                        $("#goodsCustomsStat").val('');
                                    };
                                }

                                if(isNotEmpty(bills[i].totalPackageQuantity)){
                                    if (bills[i].totalPackageQuantity.value !== null && bills[i].totalPackageQuantity.value !== undefined && bills[i].totalPackageQuantity.value !== '') {
                                        billTable['packNum']=bills[i].totalPackageQuantity.value;//货物总件数
                                    };

                                    if (bills[i].totalPackageQuantity.unitCode !== null && bills[i].totalPackageQuantity.unitCode !== undefined && bills[i].totalPackageQuantity.unitCode !== '') {
                                        billTable['packTypeCode']=bills[i].totalPackageQuantity.unitCode;//包装种类
                                    };
                                }

                                if (bills[i].transitDeparture.id !== null && bills[i].transitDeparture.id !== undefined && bills[i].transitDeparture.id !== '') {
                                    billTable['transLocationIdCode']=bills[i].transitDeparture.id;//跨境指运地
                                };


                                if(bills[i].grossVolumeMeasure!==null && bills[i].grossVolumeMeasure!==undefined){
                                    if (bills[i].grossVolumeMeasure.value !== null && bills[i].grossVolumeMeasure.value !== undefined && bills[i].grossVolumeMeasure.value !== '') {
                                        billTable['cube']=bills[i].grossVolumeMeasure.value;//货物体积
                                    };
                                }
                                if(isNotEmpty(bills[i].governmentAgencyGoodsItem)){
                                    if (bills[i].governmentAgencyGoodsItem.goodsMeasure.grossMassMeasure.value !== null && bills[i].governmentAgencyGoodsItem.goodsMeasure.grossMassMeasure.value !== undefined && bills[i].governmentAgencyGoodsItem.goodsMeasure.grossMassMeasure.value !== '') {
                                        billTable['grossWt']=bills[i].governmentAgencyGoodsItem.goodsMeasure.grossMassMeasure.value;//货物总毛重
                                    };
                                }



                                if (bills[i].valueAmount.value !== null && bills[i].valueAmount.value !== undefined && bills[i].valueAmount.value !== '') {
                                    billTable['goodsValue']=bills[i].valueAmount.value;//货物价值
                                };

                                if (bills[i].valueAmount.currencyID !== null && bills[i].valueAmount.currencyID !== undefined && bills[i].valueAmount.currencyID !== '') {
                                    billTable['currencyTypeCode']=bills[i].valueAmount.currencyID;//金额类型
                                };
                                //						i
                                if(isNotNull(bills[i].transportContractDocument.consolidator)){
                                    if (bills[i].transportContractDocument.consolidator.id !== null && bills[i].transportContractDocument.consolidator.id !== undefined && bills[i].transportContractDocument.consolidator.id !== '') {
                                        billTable['consolidatorId']=bills[i].transportContractDocument.consolidator.id;//拼箱人代码
                                    };
                                }


                                //						if (bills[i].borderTransportMeans.itinerary.routingCountryCode !== null && bills[i].borderTransportMeans.itinerary.routingCountryCode !== undefined && bills[i].borderTransportMeans.itinerary.routingCountryCode !== '') {
                                //							billTable['routingContrys']=bills[i].borderTransportMeans.itinerary.routingCountryCode;//途径国家代码数组
                                //							};

                                if (bills[i].consignee.id !== null && bills[i].consignee.id !== undefined && bills[i].consignee.id !== '') {
                                    billTable['consigneeId']=bills[i].consignee.id;//收货人代码
                                };

                                if (bills[i].consignee.name !== null && bills[i].consignee.name !== undefined && bills[i].consignee.name !== '') {
                                    billTable['consigneeName']=bills[i].consignee.name;//收货人名称
                                };

                                if (bills[i].consignee.contact.name !== null && bills[i].consignee.contact.name !== undefined && bills[i].consignee.contact.name !== '') {
                                    billTable['consigneeContactName']=bills[i].consignee.contact.name;//收货人具体联系人名称
                                };


                                if (bills[i].consignor.id !== null && bills[i].consignor.id !== undefined && bills[i].consignor.id !== '') {
                                    billTable['consignorId']=bills[i].consignor.id;//发货人代码
                                };

                                if (bills[i].consignor.name !== null && bills[i].consignor.name !== undefined && bills[i].consignor.name !== '') {
                                    billTable['consignorName']=bills[i].consignor.name;//发货人名称
                                };

                                if (bills[i].notifyParty.id !== null && bills[i].notifyParty.id !== undefined && bills[i].notifyParty.id !== '') {
                                    billTable['notifyId']=bills[i].notifyParty.id;//通知人代码
                                };

                                if (bills[i].notifyParty.name !== null && bills[i].notifyParty.name !== undefined && bills[i].notifyParty.name !== '') {
                                    billTable['notifyName']=bills[i].notifyParty.name;//通知人名称
                                };

                                if (bills[i].notifyParty.address.line !== null && bills[i].notifyParty.address.line !== undefined && bills[i].notifyParty.address.line !== '') {
                                    billTable['notifyAddr']=bills[i].notifyParty.address.line;//通知人地址
                                };

                                if (bills[i].undgcontact.name !== null && bills[i].undgcontact.name !== undefined && bills[i].undgcontact.name !== '') {
                                    billTable['undgContactName']=bills[i].undgcontact.name;//危险品联系人名称
                                };

                                if (bills[i].consignee.communication !== null && bills[i].consignee.communication !== undefined && bills[i].consignee.communication !== '') {
                                    billTable['communicationConsignee']=bills[i].consignee.communication;//收货人信息段
                                };

                                if (bills[i].consignee.contact.communication !== null && bills[i].consignee.contact.communication !== undefined && bills[i].consignee.contact.communication !== '') {
                                    billTable['communicationContact']=bills[i].consignee.contact.communication;//收货具体联系人信息段
                                };

                                if (bills[i].consignor.communication !== null && bills[i].consignor.communication !== undefined && bills[i].consignor.communication !== '') {
                                    billTable['communicationConsignor']=bills[i].consignor.communication;//发货人数据段
                                };

                                if (bills[i].notifyParty.communication !== null && bills[i].notifyParty.communication !== undefined && bills[i].notifyParty.communication !== '') {
                                    billTable['communicationNotify']=bills[i].notifyParty.communication;//通知人数据段
                                };

                                if (bills[i].undgcontact.communication !== null && bills[i].undgcontact.communication !== undefined && bills[i].undgcontact.communication !== '') {
                                    billTable['communicationUndgContact']=bills[i].undgcontact.communication;//危险品联系人数据段

                                };

                                if (bills[i].consignmentItem !== null && bills[i].consignmentItem !== undefined && bills[i].consignmentItem !== '') {
                                    billTable['consignmentItems']=bills[i].consignmentItem;//商品项数组
                                };

                                if (bills[i].transportEquipment!== null && bills[i].transportEquipment !== undefined && bills[i].transportEquipment !== '') {
                                    billTable['transportEquipments']=bills[i].transportEquipment;//集装箱数组
                                };
                                //插入提运单列表
                                $('#billOfLadingInformationTalbe').bootstrapTable('insertRow', {
                                    index: billIndex,
                                    row: billTable
                                });
                                billIndex++;

                                billTables.push(billTable);
                            }

                        };
                        $('#org_mtf_m_head_form').setForm(headForm);
                        //$('#org_bill_info').setForm(jsonData)
                        //$('#org_bill_info').setForm(jsonData)
                        resetselectFunc(json.data.resultObject);
                        $("#billNo").focus();
                    }else{
                        $("#mft_copy").attr("disabled", true);//置灰复制按钮
                        $("#customsCodeName").focus();
                        return;
                    }
                }else{
                    $("#mft_copy").attr("disabled", true);//置灰复制按钮
                    $("#customsCodeName").focus();
                    return;
                }
            }

        },
    });

    layer.close(saveMftHeadIndex);

}
//回填后请求
function resetselectFunc(_data){
    var trafModeCode = $('#trafModeCode').val();
//	var customsCode = $('#customsCode').val();
//	var customMaster = $('#customMaster').val();
    var customsCode = _data.declaration.declarationOfficeID;
    var customMaster = _data.head.senderID.trim().substring(0,4);

    /*//运输方式代码 SW_TRANSF
    if (trafModeCode !== null && trafModeCode !== undefined && trafModeCode !== '') {
        $('#trafMode').autocomp({// 隐藏框
            tableName:'SW_TRANSF',// 查询的同义词
            hiddenId:'trafModeCode',// 显示框
            keyValue:trafModeCode
        });
        } */

    //进出境口岸海关代码
    if (customsCode !== null && customsCode !== undefined && customsCode !== '') {
        $('#customsCodeName').autocomp({// 隐藏框
            tableName:'CUS_CUSTOMS',// 查询的同义词
            hiddenId:'customsCode',// 显示框
            keyValue:customsCode
        });
    }
    //传输企业备案关区
    if (customMaster !== null && customMaster !== undefined && customMaster !== '') {
        $('#customMasterName').autocomp({// 隐藏框
            tableName:'CUS_CUSTOMS',// （备案机关？申报企业关区？）
            hiddenId:'customMaster',// 显示框
            keyValue:customMaster
        });
    }



}
/**
 * 预配舱单主要数据表头信息 刷新方法
 */
function resetMftHeadFunc(){
//	$("input").removeAttr("readonly");
//	$("input").val("");
    //清空以前操作的缓存
    $('#containerInformationTalbe').bootstrapTable('removeAll');
    $('#commodityInformationTalbe').bootstrapTable('removeAll');
    $('#billOfLadingInformationTalbe').bootstrapTable('removeAll');

    $("#org_mtf_m_head_form").find("input").each(function(){
        if(this.id!="trafMode"){
            $(this).val("");
        }

    });

    $('#voyageNo').focus();
}


/**
 * 删除舱单  表头的方法
 */
function delhead(){
    layer.confirm('是否确认删除该票数据？', {icon: 7, title:'提示'}, function(index){
        // 实例化表单数据并将其转换为json格式
        var serviceName='eport.superpass.roadmft.CommonManifestDeleteService';
        var messageType='MT2401';
        var headData=$("#org_mtf_m_head_form").serializeJson();
        //console.log(headData.voyageNo);
        if(headData.voyageNo==''){
            showLayerWarnMsg("请输入货物运输批次号!", null);
            return;
        }
        var tempJson = {
            "serviceName": serviceName,
            "deleteRequest": {
                "deleteCondition": {
                    "msgType": messageType,
                    "voyageNo":headData.voyageNo
                }
            }
        };
        var saveMftHeadIndex = layer.load(1, {
            shade : [ 0.1, '#fff' ]
            // 0.1透明度的白色背景
        });

        $.ajax({
            type : "POST",
            url : BasePath+"/advanceManifest/delete?msgType="+ msgType,
            data : JSON.stringify(tempJson),
            contentType : "application/json;charset=utf-8",
            dataType : "json",
            success : function(json) {
                layer.close(saveMftHeadIndex);
                if(json.ok){
                    showLayerMsg("删除成功!", 3000);
                    clearContactInfo();
                    $("#voyageNo").attr("disabled",false);
                    resetData();
                }else{
                    var msg=json.data.msg;
                    showLayerFailMsg(msg,null);
                }

            },
            complete:function(){
                layer.close(saveMftHeadIndex);
            }
        });


    });

}


/**
 * 重置数据和按钮
 * ***/
function resetData(){
    $("#org_mtf_m_head_form").find("input").each(function(){
        if(this.id!="trafMode"&&this.id!="trafModeCode"){
            $(this).val("");
        }

    });
    $("#dataExchangeIdText").attr("readonly",true);
    billChangeFlag = false;
    $("#billOfLadingInformationTalbe").bootstrapTable("removeAll");
    clearBillFormData();
    $("#transLocationId").attr("readOnly","readOnly");//灰掉跨境启运地input框
    if(pageType==="main"){
        $("#sysRand").attr("disabled",false);
        $("#voyageNo").attr("readonly", false);
        initMainPage();
    }else if(pageType==="change"){
        $("#voyageNo").removeAttr("readonly");//提运单号
        $("#goodsCustomsStat").attr("readonly",true);//海关货物通关代码
        //提运单信息
        $("#bill_add").removeAttr("disabled");
        $("#billOfLadingInformationAddBtn").removeAttr("disabled");
        $("#delete_mft_bill").removeAttr("disabled");
        $("#bill_info_copy").removeAttr("disabled");
        $("#goodsTotal").removeAttr("disabled");
        //商品项信息
        $("#commodity_add").removeAttr("disabled");
        $("#commodity_info_save").removeAttr("disabled");
        $("#mft_goods_delete").removeAttr("disabled");
        /*$("#packNum").attr("readonly",true);//货物总件数
        $("#packType").attr("readonly",true);//包装种类代码
        $("#grossWt").attr("readonly",true);//货物总毛重
*/			initChangePage();
    }else{
        $("#voyageNo").removeAttr("readonly");
        $("#goodsCustomsStat").removeAttr("readonly");
        //提运单信息按钮
        $("#bill_add").removeAttr("disabled");
        $("#billOfLadingInformationAddBtn").removeAttr("disabled");
        $("#delete_mft_bill").removeAttr("disabled");
        $("#bill_info_copy").removeAttr("disabled");
        $("#goodsTotal").removeAttr("disabled");
        initDelPage();
    }
    //重置flag
    refreshFlags();
    refreshIndex();//重置index
    billIndex = 1;//重置提运单列表序号

}

/***************************************提运单信息**********************/
/**
 * 提运单信息暂存方法
 */
var inde=1;
function saveBillInfoFunc(){
    var customsStatCode=$("#goodsCustomsStatCode").val();
    if(customsStatCode==="RD09"||customsStatCode==="RD16"){
        if($("#transLocationId").val().length==0){
            showLayerWarnMsg("跨境启运地必填");
            return;
        }
    }
    var dataBillInfo = getAllBillInfos();
    dataBillInfo.state=false;
    dataBillInfo.index=billIndex;
    $('#billOfLadingInformationTalbe').bootstrapTable('insertRow', {
        index: billIndex,
        row: dataBillInfo
    });
    billIndex++;
    //清空表单
    clearBillFormData();
}

/*新增提运单*/

function addBillInfoFunc(){
    var billNo = $("#billNo").val();
    if(!isNotEmpty(billNo)){
        showLayerWarnMsg("提（运）单号不能为空",null);
        return;
    }
    var customsStatCode=$("#goodsCustomsStatCode").val();
    if(customsStatCode==="RD09"||customsStatCode==="RD16"){
        if($("#transLocationId").val().length==0){
            $("#transLocationId").removeAttr("readOnly");
            showLayerWarnMsg("跨境启运地必填");
            return;
        }
    }

    if(billChangeFlag){//判断是否是回显数据
        updateBillInfoFunc();//是回显，只有更新操作
        $("#billNo").attr("readonly", true);
    }else{//不是回显，根据是否选中行判断是更新还是新增
        if(billSaveFlag){//更新标记为true时 执行更新方法
            updateBillInfoFunc();//提运单更新方法
            clearBillInfo();
            refreshAllBillInfo ();
            refreshAllContact();//联系人表单清空

        }else{
            saveBillInfoFunc();
            clearBillInfo();
            refreshAllBillInfo ();
            refreshAllContact();//联系人表单清空
        }
        $("#billNo").attr("readonly", false);
        $("#billNo").focus();
    }
    refreshFlags();//重置所有更新标记
    $('#transLocationId').attr("readonly", "readonly");
    $("#consigneeContactName").attr("readonly", "readonly");

}

/**
 * 商品信息保存方法
 */

function addGoodsFunc(){
    if(billChangeFlag){//变更或删除申请回填标记  只有更新操作
        updateGoodsFunc();//商品项更新方法
        updateBillInfoFunc();//更新提运单方法
    }else{
        if(goodsInfoFlag){//当商品项更新标记为true时，执行更新方法
            updateGoodsFunc();//商品项更新方法
            goodsInfoFlag = false;//更新完后重置商品项更新标记
        }else{
            saveGoodsFunc();//商品项新增方法
        }
        clearGoodsInfo();

    }
    resetHsCodeList();
    /**
     * 商品信息保存或更新后序号重排
     * @description 商品项序号在列表显示的永远是按顺序排列的，但是已经存在对象里面的商品项序号是不会随动的，因此会产生回显
     * 时商品项序号和列表展示的序号不同，因此当列表上序号发生变化时，对象里已经存在的序号也要改变
     */
    var selects = $("#commodityInformationTalbe").bootstrapTable('getData');//获取列表所有行
    if(selects.length>0){//遍历，重新给序号赋值
        for(var i=0;i<selects.length;i++){
            selects[i].goodsSeqNo = i+1;//按顺序赋值
            $('#commodityInformationTalbe').bootstrapTable('updateRow', {
                index: i,
                row: selects[i]
            });
        }
    }
    if(billSaveFlag){//当更新标记为true时，触发提运单更新方法
        updateBillInfoFunc();
    }
}

/**
 * 新增集装箱信息方法
 */

function addContainerFunc(){
    if(containerFlag){
        updateContainerFunc();

        containerFlag = false;
    }else{
        saveContainerFunc();
    }
    refreshContainerInfo();
    if(billSaveFlag){//当提运单更新标记为true时 集装箱操作完成后更新提运单信息
        updateBillInfoFunc(); //提运单更新方法
    }
}
/**清空表格数据**/
function refreshAllBillInfo (){

    $('#containerInformationTalbe').bootstrapTable('removeAll');
    $('#commodityInformationTalbe').bootstrapTable('removeAll');
    $('#countryInfoTalbe').bootstrapTable('removeAll');
    $('#chgInfoTalbe').bootstrapTable('removeAll');
    $('#consigneeInfoTalbe').bootstrapTable('removeAll');
    $('#consigneeContactInfoTalbe').bootstrapTable('removeAll');
    $('#consignoInfoTalbe').bootstrapTable('removeAll');
    $('#notifyInfoTalbe').bootstrapTable('removeAll');
    $('#undgInfoTalbe').bootstrapTable('removeAll');
}
function getAllBillInfos(){
    //1.基本必填非必填校验
    /*if(!$("#org_bill_info").valid()){
        layer.open( {
             title:'提示信息',
             content: '必填项未填写!',
             time: 3000 //2秒关闭（如果不配置，默认是3秒）
            });
        return;
    }	*/

//1.基本必填非必填校验

    //获取id为org_bill_info的表单数据
    var dataTem=$("#org_bill_info").serializeJson();
    //商品项数组
    var consignmentItems =new Array();
    var consignmentIs=$("#commodityInformationTalbe").bootstrapTable("getData");
    if(consignmentIs.length>0){
        for(var i=0;i<consignmentIs.length;i++){
            var consignmentI = null;
            if(pageType=="change"){
                consignmentI = {
                    "sequenceNumeric": consignmentIs[i].goodsSeqNo,//商品项编号
                    "commodity": {
                        "hscode": consignmentIs[i].HSCode,//HS编码20181022 maqingsong 20181024
                        "cargoDescription": consignmentIs[i].goodsBriefDesc,//商品项描述
                        "description": consignmentIs[i].goodsDetailDesc,//商品项描述补充信息
                        "classification": { "id": consignmentIs[i].undgNo }//危险品编号
                    },
                    "goodsMeasure": {
                        "grossMassMeasure": {
                            "unitCode": "KGM",
                            "value": consignmentIs[i].goodsGrossWt//商品项毛重
                        }
                    },
                    "packaging": {
                        "quantityQuantity": {
                            "unitCode": consignmentIs[i].goodsPackTypeCode,//包装种类
                            "value": consignmentIs[i].goodsPackNum//商品项件数
                        }
                    }
//				          },
//				          "customsTransitCode":consignmentIs[i].customsTransitCode
                };
            }else{
                consignmentI = {
                    "sequenceNumeric": consignmentIs[i].goodsSeqNo,//商品项编号
                    "commodity": {
                        "hscode": consignmentIs[i].HSCode,//HS编码20181022 maqingsong 20181014
                        "cargoDescription": consignmentIs[i].goodsBriefDesc,//商品项描述
                        "description": consignmentIs[i].goodsDetailDesc,//商品项描述补充信息
                        "classification": { "id": consignmentIs[i].undgNo }//危险品编号
                    },
                    "goodsMeasure": {
                        "grossMassMeasure": {
                            "unitCode": "KGM",
                            "value": consignmentIs[i].goodsGrossWt//商品项毛重
                        }
                    },
                    "packaging": {
                        "quantityQuantity": {
                            "unitCode": consignmentIs[i].goodsPackTypeCode,//包装种类
                            "value": consignmentIs[i].goodsPackNum//商品项件数
                        }
                    }
//				          },
//				          "customsTransitCode":consignmentIs[i].customsTransitCode
                };
            }


            consignmentItems.push(consignmentI);
        }
    }

    if(pageType=="main"){
        //集装箱数组
        var transportEquipments=new Array();
        var transportEs=$("#containerInformationTalbe").bootstrapTable("getData");
        for(var i=0;i<transportEs.length;i++){
            var transportE = {
                "characteristicCode": transportEs[i].contaSizeTypeCode,//尺寸和类型
                "fullnessCode":transportEs[i].contaLoadedTypeCode,//重箱空箱标识
                "id": transportEs[i].contaId,//集装箱器编号
                "supplierPartyTypeCode": transportEs[i].contaSuppIdCode//来源代码
            };

            transportEquipments.push(transportE);

        }

    }

//更改原因代码
    var chgCodeNames =new Array();
    var chgCodes=$("#chgInfoTalbe").bootstrapTable("getData");
    if(pageType=="change"||pageType=="delete"){
        if(chgCodes.length<1){
            showLayerWarnMsg("变更原因必填",null);
            return;
        }
        if(changeInformationSwitch){
            var reason = $("#reason").val();
            var contact = $("#contact").val();
            var phone = $("#phone").val();
            var billNo = $("#billNo").val();
            if(!isNotNull(reason)){//提运单号非空判断
                showLayerWarnMsg("提运单 "+billNo+" 变更原因描述不能为空");
                return;
            }
            if(!isNotNull(contact)){//提运单号非空判断
                showLayerWarnMsg("提运单 "+billNo+" 变更申请联系人姓名不能为空");
                return;
            }
            if(!isNotNull(phone)){//提运单号非空判断
                showLayerWarnMsg("提运单 "+billNo+" 变更申请联系人电话不能为空");
                return;
            }
        }else{
            var billNo = $("#billNo").val();
            var array = ["#reason","#contact","#phone"];
            var count = new Array();
            for(var i = 0; i < 3; i++){
                if(isNotNull($(array[i]).val())){
                    count.push(array[i]);
                }
            }
            if(count.length > 0 && count.length < 3){
                if(!isNotNull($(array[0]).val())){//提运单号非空判断
                    showLayerWarnMsg("提运单 "+billNo+" 变更原因描述不能为空");
                    return;
                }
                if(!isNotNull($(array[1]).val())){//提运单号非空判断
                    showLayerWarnMsg("提运单 "+billNo+" 变更申请联系人姓名不能为空");
                    return;
                }
                if(!isNotNull($(array[2]).val())){//提运单号非空判断
                    showLayerWarnMsg("提运单 "+billNo+" 变更申请联系人电话不能为空");
                    return;
                }
            }
        }
        if(checkChangeInformation()){
            return;
        }
    }
    for(var i=0;i<chgCodes.length;i++){
        var chgCode = chgCodes[i].amendmentSeq;
        chgCodeNames.push(chgCode);
    }
//途径国家代码
    var routingContrys =new Array();
    var routingCs=$("#countryInfoTalbe").bootstrapTable("getData");
    for(var i=0;i<routingCs.length;i++){
        var routingC = routingCs[i].routingContryIdTextCode;
        routingContrys.push(routingC);
    }
//各种联系人数组
//收货人信息数组
    var communicationConsignee =new Array();
    var communications=$("#consigneeInfoTalbe").bootstrapTable("getData");
//console.log(communications);
    for(var i=0;i<communications.length;i++){
        var communication = {
            "id": communications[i].communicationNo,
            "typeID": communications[i].communicationType
        };

        communicationConsignee.push(communication);
    }
//收货具体联系人信息数组
    var communicationContact =new Array();
    var communicationContacts=$("#consigneeContactInfoTalbe").bootstrapTable("getData");
    for(var i=0;i<communicationContacts.length;i++){
        var communication = {
            "id": communicationContacts[i].communicationNo,
            "typeID": communicationContacts[i].communicationTypej
        };

        communicationContact.push(communication);
    }
//发货人信息数组
    var communicationConsignor =new Array();
    var communicationConsignors=$("#consignoInfoTalbe").bootstrapTable("getData");
    for(var i=0;i<communicationConsignors.length;i++){
        var communication = {
            "id": communicationConsignors[i].communicationNo,
            "typeID": communicationConsignors[i].communicationTypef
        };

        communicationConsignor.push(communication);
    }
//通知人人信息数组
    var communicationNotify =new Array();
    var communicationNotifys=$("#notifyInfoTalbe").bootstrapTable("getData");

    for(var i=0;i<communicationNotifys.length;i++){
        var communication = {
            "id": communicationNotifys[i].communicationNo,
            "typeID": communicationNotifys[i].communicationTypet
        };

        communicationNotify.push(communication);
    }
//危险品联系人信息数组
    var communicationUndgContact =new Array();
    var communicationUndgContacts=$("#undgInfoTalbe").bootstrapTable("getData");
    for(var i=0;i<communicationUndgContacts.length;i++){
        var communication = {
            "id": communicationUndgContacts[i].communicationNo,
            "typeID": communicationUndgContacts[i].communicationTypew
        };

        communicationUndgContact.push(communication);
    }

//联系人表单序列化
//收货人表单序列化
    var consigneeData=$("#consignee_info_form").serializeJson();
//console.log(consigneeData);
//具体联系人
    var consigneeContactData=$("#consigneeContact_info_form").serializeJson();
//发货人
    var consignorData=$("#consignor_info_form").serializeJson();
//通知人
    var notifyData=$("#notify_info_form").serializeJson();
//危险品联系人
    var undgData=$("#undg_info_form").serializeJson();
//构建一个大json对象开始
    var dataBillInfo = $.extend({}, dataTem, consigneeData,consigneeContactData,consignorData,notifyData,undgData);
    dataBillInfo['communicationConsignee']=communicationConsignee;
    dataBillInfo['communicationContact']=communicationContact;
    dataBillInfo['communicationConsignor']=communicationConsignor;
    dataBillInfo['communicationNotify']=communicationNotify;
    dataBillInfo['communicationUndgContact']=communicationUndgContact;
    dataBillInfo['routingContrys']=routingContrys;
    dataBillInfo['chgCodeNames']=chgCodeNames;
    dataBillInfo['transportEquipments']=transportEquipments;
    dataBillInfo['consignmentItems']=consignmentItems;

    //1205 谢霖志 新增无纸化变更需求
    dataBillInfo['reason'] = $("#reason").val();
    dataBillInfo['contact'] = $("#contact").val();
    dataBillInfo['phone'] = $("#phone").val();
    //1205 谢霖志
    //构建大Json对象结束
    return dataBillInfo;

}
//所有联系人刷新
function refreshAllContact(){
    $("#consignee_info_form")[0].reset();
    $("#consignee_info_form").find("input").each(function(){
        $(this).val("");
    });
    $("#consigneeContact_info_form")[0].reset();
    $("#consigneeContact_info_form").find("input").each(function(){
        $(this).val("");
    });
    $("#consignor_info_form")[0].reset();
    $("#consignor_info_form").find("input").each(function(){
        $(this).val("");
    });
    $("#notify_info_form")[0].reset();
    $("#notify_info_form").find("input").each(function(){
        $(this).val("");
    });
    $("#undg_info_form")[0].reset();
    $("#undg_info_form").find("input").each(function(){
        $(this).val("");
    });
};

/*点击 详情弹出表单
$("body").delegate("#billOfLadingInformationTalbe a", 'click', function () {
    openBillFormFunc(data);
});
/**
 * 删除提运单的方法
 */
function delBill(){

    var selects = $("#billOfLadingInformationTalbe").bootstrapTable('getSelections');
    if (selects.length == 0) {
        layer.confirm('请勾选需删除的数据', {icon: 7, title:'提示'}, function(index){ //3提示图标
            layer.close(index);
        });
        return;
    }else{
        layer.confirm('是否确认删除该数据？', {icon: 7, title:'提示'}, function(index){ //3提示图标
            var listArr=[];
            for(var a=0;a<selects.length;a++){
                var s= selects[a].state;
                listArr.push(s);
                //console.log(s);
                $('#billOfLadingInformationTalbe').bootstrapTable('remove',{field: 'state', values: listArr});

                //发送提交请求

                layer.close(index);
                showLayerMsg('操作成功！')
            }
            billIndex--;
            refreshFlags();
            clearBillInfo();//清空表单
            refreshAllContact();//清空各联系人
            refreshIndex();//重置Index

        });
        $("#billNo").attr("readonly", false);
        $('#transLocationId').attr("readonly", "readonly");
        $("#consigneeContactName").attr("readonly", "readonly");
    }
}
/*刷新序列值*/
function refreshIndex(){
    contaIndex = 1;//集装箱列表序号
    commodityIndex = 1;//商品
    chgIndex = 1;//变更原因
    consigneeIndex = 1;//收货人
    consigneeContactIndex = 1;//收货具体联系人
    consignorIndex = 1;//发货人
    notifyIndex = 1;//通知人
    undgIndex = 1;//危险品联系人
}
//初始化Flags
function refreshFlags(){
    billSaveFlag = false;
    containerFlag = false;
    goodsInfoFlag = false;
    chgFlag = false;//变更原因执行更新方法标记
    consigneeFlag = false;//收货人执行更新方法标记
    updateconsigneeContactIndexFlag = false;//收货具体联系人执行更新方法标记
    consignorFlag = false;//发货人执行更新方法标记
    notifyFlag = false;//通知人执行更新方法标记
    undgFlag = false;//危险品联系人执行更新方法标记
}
/*查看集装箱详情*/
function lookContasInfo(data,element){
    if(typeof data == 'number'){//1点击链接查看入口
        dataTemp = $('#containerInformationTalbe').bootstrapTable('getData')[data];
        var trueIndex=$($(element).children()[2]).text();//获取页面中的商品序列号值
        if(dataTemp){
            $('#mft_bill_container_form').setForm(dataTemp);
            $("#contaId").val(trueIndex);
            $('#goodsSeqNo').attr('readonly', true);
            //货物商品里的如果可输可选 如果遇到参数库没有的字段 反填情况
            var undgNo = $('#undgNo').val();
            //危险品编号
            if (undgNo !== null && undgNo !== undefined && undgNo !== '') {
                $('#undgNoName').autocomp({// 显示框
                    tableName:'CUS_MFT8_DAN_GOODS',// 查询的同义词
                    hiddenId:'undgNo',// 隐藏框
                    keyValue:undgNo
                });
            }

            return;
        }else{
            showLayerWarnMsg("打开详情信息失败，请刷新重试！");
            return;
        }
    }
}

/**
 *   打开提运单 详情
 */
function openBillFormFunc(data){

    if(typeof data == 'number'){
        data = $('#billOfLadingInformationTalbe').bootstrapTable('getData')[data];
        //先清空
        clearBillFormData();
        if(data){
            $('#org_bill_info').setForm(data);	//提运单表单
            if(data.goodsCustomsStatCode=="RD09"||data.goodsCustomsStatCode=="RD16"){
                if(pageType=="delete"){
                    $("#transLocationId").attr("readOnly","readonly");
//					$("#customsTransit").attr("readOnly","readonly");
                }else{
                    $("#transLocationId").removeAttr("readOnly");
//					$("#customsTransit").removeAttr("readOnly");

//					$("#customsTransit").removeClass();
//					$("#customsTransit").addClass("form-control non-empty");
                }
            }else{
                $('#transLocationId').attr('readonly', true);
                $("#transLocationIdCode").val('');//清空隐藏框
                $("#transLocationId").val('');//清空显示框
//		    	 $("#customsTransit").attr("readonly","readonly")
//		    	 $("#customsTransitCode").val('');//清空隐藏框
//		    	 $("#customsTransit").val('');//清空显示框
            }
            if(isNotNull(data.consigneeName)){//回显时 如果收货人名称存在，激活收货具体联系人名称录入框
                $("#consigneeContactName").removeAttr("readOnly");
            }else{
                $("#consigneeContactName").attr("readOnly", "readOnly");
                clearConsigneeContactInfo();
            }
            $('#consignee_info_form').setForm(data);  //收货人
            $('#consigneeContact_info_form').setForm(data);//具体收货人
            $('#consignor_info_form').setForm(data);//发货人
            $('#notify_info_form').setForm(data);//通知人
            $('#undg_info_form').setForm(data);//危险品联系人
            /*$("#billNo").attr("readonly",true);	*/

            //1205 谢霖志 新增变更无纸化需求
            $("#reason").val(data.reason);
            $("#phone").val(data.phone);
            $("#contact").val(data.contact);
            //1205
            //展示集装箱列表
            if (data.transportEquipments !== null && data.transportEquipments !== undefined && data.transportEquipments !== '') {
                for(var i=0;i<data.transportEquipments.length;i++){
                    var transportEquipment={};
                    if (data.transportEquipments[i].id !== null && data.transportEquipments[i].id !== undefined && data.transportEquipments[i].id !== '') {
                        transportEquipment['contaId']=data.transportEquipments[i].id;//集装箱（器）编号
                    }
                    if (data.transportEquipments[i].characteristicCode !== null && data.transportEquipments[i].characteristicCode !== undefined && data.transportEquipments[i].characteristicCode !== '') {
                        transportEquipment['contaSizeTypeCode']=data.transportEquipments[i].characteristicCode;//尺寸和类型
                        if(isNotNull(data.transportEquipments[i].characteristicCode)){
                            $('#contaSizeType').autocomp2({// 显示框
                                tableName:'CUS_MFT8_EQUIP_SIZE_TYPE',// 查询的同义词
                                hiddenId:'contaSizeTypeCode',// 隐藏框
                                keyValue:data.transportEquipments[i].characteristicCode
                            });
                        }


                        transportEquipment['contaSizeType']=$("#contaSizeType").val();
                        $("#contaSizeType").val('');
                    }
                    if (data.transportEquipments[i].supplierPartyTypeCode !== null && data.transportEquipments[i].supplierPartyTypeCode !== undefined && data.transportEquipments[i].supplierPartyTypeCode !== '') {
                        transportEquipment['contaSuppIdCode']=data.transportEquipments[i].supplierPartyTypeCode;//来源代码
                        if(isNotNull(data.transportEquipments[i].supplierPartyTypeCode)){
                            $('#contaSuppId').autocomp2({// 显示框
                                tableName:'CUS_MFT8_EQUIP_SUP',// 查询的同义词
                                hiddenId:'contaSuppIdCode',// 隐藏框
                                keyValue:data.transportEquipments[i].supplierPartyTypeCode
                            });
                        }


                        transportEquipment['contaSuppId']=$("#contaSuppId").val();
                        $("#contaSuppId").val('');
                    }
                    if (data.transportEquipments[i].fullnessCode !== null && data.transportEquipments[i].fullnessCode !== undefined && data.transportEquipments[i].fullnessCode !== '') {
                        transportEquipment['contaLoadedTypeCode']=data.transportEquipments[i].fullnessCode;//重箱空箱标识
                        if(isNotNull(data.transportEquipments[i].fullnessCode)){
                            $('#contaLoadedType').autocomp2({// 显示框
                                tableName:'CUS_MFT8_EQUIP_FULL',// 查询的同义词
                                hiddenId:'contaLoadedTypeCode',// 隐藏框
                                keyValue:data.transportEquipments[i].fullnessCode
                            });
                        }


                        transportEquipment['contaLoadedType']=$("#contaLoadedType").val();
                        $("#contaLoadedType").val('');
                    }
                    $('#containerInformationTalbe').bootstrapTable('insertRow', {
                        index: contaIndex,
                        row: transportEquipment
                    });
                    contaIndex++;
                }
            };
            //展示商品项列表
            if (data.consignmentItems !== null && data.consignmentItems !== undefined && data.consignmentItems !== '') {
                for(var i=0;i<data.consignmentItems.length;i++){
                    var consignmentItem={};
                    if (data.consignmentItems[i].sequenceNumeric !== null && data.consignmentItems[i].sequenceNumeric !== undefined && data.consignmentItems[i].sequenceNumeric !== '') {
                        consignmentItem['goodsSeqNo']=data.consignmentItems[i].sequenceNumeric;//商品项序号
                    }
//					if(data.consignmentItems[i].customsTransitCode !==null && data.consignmentItems[i].customsTransitCode !== undefined && data.consignmentItems[i].customsTransitCode !=''){
//						consignmentItem['customsTransitCode']=data.consignmentItems[i].customsTransitCode;//转关类型
//						$('#customsTransit').autocomp7({// 显示框
//							tableName:'PARA_CUSTOMS_TRANSIT_TYPE',// 查询的同义词
//							hiddenId:'customsTransitCode',// 隐藏框
//							keyValue:data.consignmentItems[i].customsTransitCode
//						});
//						consignmentItem['customsTransit']=$("#customsTransit").val();
//						$("#customsTransit").val('');
//					}
                    if(isNotNull(data.consignmentItems[i].packaging.quantityQuantity)){
                        if(isNotNull(data.consignmentItems[i].packaging.quantityQuantity.value)){
                            consignmentItem['goodsPackNum']=data.consignmentItems[i].packaging.quantityQuantity.value;//商品项件数
                        }
                        if(isNotNull(data.consignmentItems[i].packaging.quantityQuantity.unitCode)){
                            consignmentItem['goodsPackTypeCode']=data.consignmentItems[i].packaging.quantityQuantity.unitCode;//包装种类
                            if(isNotNull(data.consignmentItems[i].packaging.quantityQuantity.unitCode)){
                                $('#goodsPackType').autocomp2({// 显示框
                                    tableName:'CUS_MFT8_PACKAGING',// 查询的同义词
                                    hiddenId:'goodsPackTypeCode',// 隐藏框
                                    keyValue:data.consignmentItems[i].packaging.quantityQuantity.unitCode
                                });
                            }
                            consignmentItem['goodsPackType']=$("#goodsPackType").val();
                            $("#goodsPackType").val('');
                        }
                    }

                    if (data.consignmentItems[i].goodsMeasure.grossMassMeasure.value !== null && data.consignmentItems[i].goodsMeasure.grossMassMeasure.value !== undefined && data.consignmentItems[i].goodsMeasure.grossMassMeasure.value !== '') {
                        consignmentItem['goodsGrossWt']=data.consignmentItems[i].goodsMeasure.grossMassMeasure.value;//商品项毛重
                    }
                    if (data.consignmentItems[i].commodity.hscode!== null && data.consignmentItems[i].commodity.hscode !== undefined && data.consignmentItems[i].commodity.hscode !== '') {//回显HS编码
                        consignmentItem['HSCode']=data.consignmentItems[i].commodity.hscode;//商品项描述
                    }
                    //20181024
                    if (data.consignmentItems[i].commodity.cargoDescription !== null && data.consignmentItems[i].commodity.cargoDescription !== undefined && data.consignmentItems[i].commodity.cargoDescription !== '') {
                        consignmentItem['goodsBriefDesc']=data.consignmentItems[i].commodity.cargoDescription;//商品项描述
                    }
                    if (data.consignmentItems[i].commodity.classification.id !== null && data.consignmentItems[i].commodity.classification.id !== undefined && data.consignmentItems[i].commodity.classification.id !== '') {
                        consignmentItem['undgNo']=data.consignmentItems[i].commodity.classification.id;//危险品编号
                    }
                    if (data.consignmentItems[i].commodity.description !== null && data.consignmentItems[i].commodity.description !== undefined && data.consignmentItems[i].commodity.description !== '') {
                        consignmentItem['goodsDetailDesc']=data.consignmentItems[i].commodity.description;//商品项描述补充信息
                    }
                    $('#commodityInformationTalbe').bootstrapTable('insertRow', {
                        index: commodityIndex,
                        row: consignmentItem
                    });
                    commodityIndex++;
                }
            };
            //更改原因列表
            if (data.chgCodeNames !== null && data.chgCodeNames !== undefined && data.chgCodeNames !== '') {
                for(var i=0;i<data.chgCodeNames.length;i++){
                    var chgCodeName={};
                    chgCodeName["amendmentSeq"]=data.chgCodeNames[i];
                    if(isNotNull(data.chgCodeNames[i])){
                        $('#chgCodeText').autocomp2({// 隐藏框
                            tableName:'CUS_MFT8_CHANGE_REASON',// 查询的同义词
                            hiddenId:'amendmentSeq',// 显示框
                            keyValue:data.chgCodeNames[i]
                        });
                    }

                    chgCodeName["chgCodeText"]=	$("#chgCodeText").val();

                    $('#chgInfoTalbe').bootstrapTable('insertRow', {
                        index: chgIndex,
                        row: chgCodeName
                    });
                    chgIndex++;
                }

                $("#chgCodeText").val("");
            };
            //途径国家列表
            /*if (data.routingContrys !== null && data.routingContrys !== undefined && data.routingContrys !== '') {
                    for(var i=0;i<data.routingContrys.length;i++){
                        var routingContry={};
                        routingContry["routingContryIdTextCode"]=data.routingContrys[i];

                        $('#routingContryIdText').autocomp2({// 隐藏框
                            tableName:'CUS_MFT8_COUNTRY_CODE',// 查询的同义词
                            hiddenId:'routingContryIdTextCode',// 显示框
                            keyValue:data.routingContrys[i]
                        });
                        routingContry["routingContryIdText"]=$("routingContryIdText").val();
                        $('#countryInfoTalbe').bootstrapTable('insertRow', {
                            index: inde,
                            row: routingContry
                       });
                    }
                    };*/
            //收货人列表
            if (data.communicationConsignee !== null && data.communicationConsignee !== undefined && data.communicationConsignee !== '') {
                for(var i=0;i<data.communicationConsignee.length;i++){
                    var Consignee={};
                    Consignee["communicationNo"]=data.communicationConsignee[i].id;
                    Consignee["communicationType"]=data.communicationConsignee[i].typeID;
                    if(isNotNull(data.communicationConsignee[i].typeID)){
                        $('#communicationTypeText').autocomp2({// 显示框
                            tableName:'CUS_MFT8_COMMUNI_TYPE',// 查询的同义词
                            hiddenId:'communicationType',// 显示框
                            keyValue:data.communicationConsignee[i].typeID
                        });
                    }

                    Consignee["communicationTypeText"]=$('#communicationTypeText').val();
                    $('#consigneeInfoTalbe').bootstrapTable('insertRow', {
                        index: inde,
                        row: Consignee
                    });
                }
                $('#communicationTypeText').val("");
            };
            //收货具体人列表
            if (data.communicationContact !== null && data.communicationContact !== undefined && data.communicationContact !== '') {
                for(var i=0;i<data.communicationContact.length;i++){
                    var communicationC={};
                    communicationC["communicationNo"]=data.communicationContact[i].id;
                    communicationC["communicationTypej"]=data.communicationContact[i].typeID;
                    if(isNotNull(data.communicationContact[i].typeID)){
                        $('#communicationTypeTextj').autocomp2({// 显示框
                            tableName:'CUS_MFT8_COMMUNI_TYPE',// 查询的同义词
                            hiddenId:'communicationTypej',// 显示框
                            keyValue:data.communicationContact[i].typeID
                        });
                    }

                    communicationC["communicationTypeTextj"]=$('#communicationTypeTextj').val();

                    $('#consigneeContactInfoTalbe').bootstrapTable('insertRow', {
                        index: inde,
                        row: communicationC
                    });
                }
                $('#communicationTypeTextj').val("");
            };
            //发货人列表
            if (data.communicationConsignor !== null && data.communicationConsignor !== undefined && data.communicationConsignor !== '') {
                for(var i=0;i<data.communicationConsignor.length;i++){
                    var communicationConsig={};
                    communicationConsig["communicationNo"]=data.communicationConsignor[i].id;
                    communicationConsig["communicationTypef"]=data.communicationConsignor[i].typeID;
                    if(isNotNull(data.communicationConsignor[i].typeID)){
                        $('#communicationTypeTextf').autocomp2({// 显示框
                            tableName:'CUS_MFT8_COMMUNI_TYPE',// 查询的同义词
                            hiddenId:'communicationTypef',// 隐藏框
                            keyValue:data.communicationConsignor[i].typeID
                        });
                    }

                    communicationConsig["communicationTypeTextf"]=$('#communicationTypeTextf').val();
                    $('#consignoInfoTalbe').bootstrapTable('insertRow', {
                        index: inde,
                        row: communicationConsig
                    });
                }
                $('#communicationTypeTextf').val("");
            };
            //通知人列表
            if (data.communicationNotify !== null && data.communicationNotify !== undefined && data.communicationNotify !== '') {
                for(var i=0;i<data.communicationNotify.length;i++){
                    var communicationN={};
                    communicationN["communicationNo"]=data.communicationNotify[i].id;
                    if(data.communicationNotify[i].typeID!=undefined&&data.communicationNotify[i].typeID!=''&&data.communicationNotify[i].typeID!=null){
                        communicationN["communicationTypet"]=data.communicationNotify[i].typeID;
                        $('#communicationTypeTextt').autocomp2({// 显示框
                            tableName:'CUS_MFT8_COMMUNI_TYPE',// 查询的同义词
                            hiddenId:'communicationTypet',// 隐藏框
                            keyValue:data.communicationNotify[i].typeID
                        });


                    }

                    communicationN["communicationTypeTextt"]=$('#communicationTypeTextt').val();
                    $('#notifyInfoTalbe').bootstrapTable('insertRow', {
                        index: inde,
                        row: communicationN
                    });
                }
                $('#communicationTypeTextt').val("");
            };
            //危险品联系人列表
            if (data.communicationUndgContact !== null && data.communicationUndgContact !== undefined && data.communicationUndgContact !== '') {
                for(var i=0;i<data.communicationUndgContact.length;i++){
                    var communicationUndgC={};
                    communicationUndgC["communicationNo"]=data.communicationUndgContact[i].id;
                    if(isNotEmpty(data.communicationUndgContact[i].typeID)){
                        communicationUndgC["communicationTypew"]=data.communicationUndgContact[i].typeID;
                        $('#communicationTypeTextw').autocomp2({// 显示框
                            tableName:'CUS_MFT8_COMMUNI_TYPE',// 查询的同义词
                            hiddenId:'communicationTypew',// 隐藏框
                            keyValue:data.communicationUndgContact[i].typeID
                        });


                    }

                    communicationUndgC["communicationTypeTextw"]=$('#communicationTypeTextw').val();
                    $('#undgInfoTalbe').bootstrapTable('insertRow', {
                        index: inde,
                        row: communicationUndgC
                    });
                }
                $('#communicationTypeTextw').val("");
            };

            //下拉参数回填
            var conditionCode = $('#conditionCode').val();
            var paymentTypeCode = $('#paymentTypeCode').val();

            var goodsCustomsStatCode = $('#goodsCustomsStatCode').val();
            var transLocationIdCode = $('#transLocationIdCode').val();
            var packTypeCode = $('#packTypeCode').val();
            var currencyTypeCode = $('#currencyTypeCode').val();
            var goodsPackTypeCode = $('#goodsPackTypeCode').val();

            //运输条款
            if (conditionCode !== null && conditionCode !== undefined && conditionCode !== '') {
                $('#conditionCodeName').autocomp({// 隐藏框
                    tableName:'CUS_MFT8_CONTR_CAR_COND',// 查询的同义词
                    hiddenId:'conditionCode',//
                    keyValue:conditionCode
                });
            }
            //运费支付方法
            if (paymentTypeCode !== null && paymentTypeCode !== undefined && paymentTypeCode !== '') {
                $('#paymentType').autocomp({// 隐藏框
                    tableName:'CUS_MFT8_ROAD_PAYMENT_METHOD',// 查询的同义词
                    hiddenId:'paymentTypeCode',// 显示框
                    keyValue:paymentTypeCode
                });
            }

            //海关货物通关代码
            if (goodsCustomsStatCode !== null && goodsCustomsStatCode !== undefined && goodsCustomsStatCode !== '') {
                $('#goodsCustomsStat').autocomp({// 隐藏框
                    tableName:'CUS_MFT8_ROAD_CUSTOMS_STATUS',// 查询的同义词
                    hiddenId:'goodsCustomsStatCode',// 显示框
                    keyValue:goodsCustomsStatCode
                });
            }
            //跨境指运地
            if (transLocationIdCode !== null && transLocationIdCode !== undefined && transLocationIdCode !== '') {
                $('#transLocationId').autocomp2({// 隐藏框
                    tableName:'CUS_CUSTOMS',// 查询的同义词
                    hiddenId:'transLocationIdCode',// 隐藏框
                    keyValue:transLocationIdCode
                });
            }

            //包装种类
            if (packTypeCode !== null && packTypeCode !== undefined && packTypeCode !== '') {
                $('#packType').autocomp({// 隐藏框
                    tableName:'CUS_MFT8_PACKAGING',// 运输工具包装种类？
                    hiddenId:'packTypeCode',// 隐藏框
                    keyValue:packTypeCode
                });
            }
            //金额类型
            if (currencyTypeCode !== null && currencyTypeCode !== undefined && currencyTypeCode !== '') {
                $('#currencyType').autocomp({// 隐藏框
                    tableName:'CUS_MFT8_ROAD_CURR',// 查询的同义词
                    hiddenId:'currencyTypeCode',// 显示框
                    keyValue:currencyTypeCode
                });
            }

            //包装种类
            /*if (goodsPackTypeCode !== null && goodsPackTypeCode !== undefined && goodsPackTypeCode !== '') {
                $('#goodsPackType').autocomp({// 显示框
                    tableName:'CUS_MFT8_PACKAGING',// 查询的同义词
                    hiddenId:'goodsPackTypeCode',// 隐藏框
                    keyValue:goodsPackTypeCode
                });
                } */


        }else{
            showLayerWarnMsg("打开详情信息失败，请刷新重试！");
            return;
        }
    }

    $("#billNo").focus();
}
//清除提运单信息
function clearBillInfo(){
    $('#containerInformationTalbe').bootstrapTable('removeAll');
    $('#commodityInformationTalbe').bootstrapTable('removeAll');
    $('#org_bill_info')[0].reset();

    //1205 谢霖志 新增变更需求
    $("#reason").val("");
    $("#phone").val("");
    $("#contact").val("");
    //1205 谢霖志 新增变更需求
    clearGoodsInfo();
    refreshContainerInfo();
    //清提运单的隐藏域，
    $("#org_bill_info").find("input").each(function(){
        $(this).val("");
    });

}



//清除商品信息缓存
function clearGoodsInfo(){
    $("#mft_goods_info_form")[0].reset();
    $("#mft_goods_info_form").find("input").each(function(){
        $(this).val("");
    });
    $("#HSCode").removeClass("autocompleter-node");
    $("#HSCode").next().empty();//移除之前的下拉选节点，不然一直是之前缓存的数据
}
/**
 * 保存集装箱信息方法
 */
function saveContainerFunc(){
    var listNo = $("#listNo").val();
    //1.基本必填非必填校验
    if(!$("#mft_bill_container_form").valid()){
        return;
    }

    var dataTemp = $("#mft_bill_container_form").serializeJson();
    dataTemp["billNo"] = $('#billNo').val();
    dataTemp.state=false;
    dataTemp.index=inde;
    //添加数据到json串

    $('#containerInformationTalbe').bootstrapTable('insertRow', {
        index: inde,
        row: dataTemp
    });
    inde++;
//	   refreshContainerInfo();
    layer.close();

}

/**
 * 集装箱信息 刷新
 */
function refreshContainerInfo(){
    $("#mft_bill_container_form")[0].reset();
    $("#mft_bill_container_form").find("input").each(function(){
        $(this).val("");
    });
    $("#contaSizeType").val("");
    $("#contaSeqNo").val("");
    $("#contaSuppId").val("");
    $("#contaLoadedType").val("");
    if(pageType !="change"){
        $("#contaId").removeAttr("readonly");
    }
}
/**
 * 集装箱信息删除
 */
function delContainer(){
    var selections = $("#containerInformationTalbe").bootstrapTable('getSelections');
    if (selections.length == 0) {
        layer.confirm('请勾选需删除的数据', {icon: 7, title:'提示'}, function(index){ //3提示图标
            layer.close(index);
        });
        return;
    }else{
        layer.confirm('是否确认删除该数据？', {icon: 7, title:'提示'}, function(index){ //3提示图标
            var listArr = [];
            for(var a=0;a<selections.length;a++){
                var s= selections[a].state;
                listArr.push(s);
                $('#containerInformationTalbe').bootstrapTable('remove',{field: 'state', values: listArr});
                layer.close(index);
                showLayerMsg('操作成功！')
                contaIndex--;
            }
            refreshContainerInfo();
            containerFlag = false;
            if(billSaveFlag){
                updateBillInfoFunc();
            }
            layer.close();
        });

    }
}

var goodsIndex=1;
/**
 * 商品信息保存方法
 */
function saveGoodsFunc(){
    var dataTemp = $("#mft_goods_info_form").serializeJson();
    dataTemp.state=false;
    dataTemp.index=commodityIndex;
    dataTemp.goodsSeqNo = dataTemp.index;
    //添加数据到json串
    $('#commodityInformationTalbe').bootstrapTable('insertRow', {
        index: commodityIndex,
        row: dataTemp
    });

    commodityIndex++;
}
/**
 * 删除商品信息的方法
 */
function delGoods(){
    var selections = $("#commodityInformationTalbe").bootstrapTable('getSelections');
    if (selections.length == 0) {
        layer.confirm('请勾选需删除的数据', {icon: 7, title:'提示'}, function(index){ //3提示图标
            layer.close(index);
        });
        return;
    }else{
        layer.confirm('是否确认删除该数据？', {icon: 7, title:'提示'}, function(index){ //3提示图标
            var listArr = [];
            //获取选中的提运单
            for(var a=0;a<selections.length;a++){
                var s= selections[a].state;
                listArr.push(s);
                $('#commodityInformationTalbe').bootstrapTable('remove',{field: 'state', values: listArr});
                layer.close(index);
                showLayerMsg('操作成功！')
            }
            clearGoodsInfo();
            goodsInfoFlag = false;//删除数据后商品项更新标记重置
            //删除数据后序号重排
            var selects = $("#commodityInformationTalbe").bootstrapTable('getData');//获取列表所有行
            if(selects.length>0){//遍历，重新给序号赋值
                for(var i=0;i<selects.length;i++){
                    selects[i].goodsSeqNo = i+1;
                    $('#commodityInformationTalbe').bootstrapTable('updateRow', {//更新序号
                        index: i,
                        row: selects[i]
                    });
                }
            }
            if(billSaveFlag){
                updateBillInfoFunc();
            }
            commodityIndex--;
            layer.close(index);
        });
    }
}


function indexFormatter(value, row, index) {
    return index + 1;
}

/**
 * 复制数据保存
 */
function copyBillSaveInfoFunc(s){
    if(!$("#copy_info_form").valid()){
        return;
    }
    var selects = $("#billOfLadingInformationTalbe").bootstrapTable('getSelections');
    var dataTempArray = $.extend(true, [], selects);
    var dataTemp=dataTempArray[0];
    if(!selects.length>0){
        showLayerWarnMsg('请选中一行数据');
        return;
    }
    if(selects.length>1){
        showLayerWarnMsg('选中数据超过一行');
        return;
    }
    dataTemp.state=false;
    dataTemp.index=billIndex;
    dataTemp.billNo='';
    //dataTemp.consignorName=$("#consignorName").val();
    //添加数据到json串
    $('#billOfLadingInformationTalbe').bootstrapTable('insertRow', {
        index: billIndex,

        row: dataTemp
    });
    //复制后回显当前复制行信息
    var copBill=$("#billOfLadingInformationTalbe").children("tbody").children(":last");
    var i=$(copBill).data('index');//复制数据所在行的位置
    openBillFormFunc(i);//展示复制后打数据
    billSaveFlag = true;//更新标记改为true，操作表单数据即为修改复制后打数据
    updateIndex = i;//用来指定更新哪行
    billIndex++;

}
/**
 * 汇总页面打开方法
 */
function copyBillInfoFunc(){
    var selects = $('#billOfLadingInformationTalbe').bootstrapTable("getData");

    var totalgoodQuantity=0;
    var totalgoodsWeightNew=0;
    if(selects.length>0){
        for(var a=0;a<selects.length;a++){
            var s = selects[a];

            var goodQuantity = s.packNum;
            var goodsWeight=s.grossWt;
            var goodQuantityInt=parseFloat(goodQuantity);
            var goodsWeightInt=parseFloat(goodsWeight);
            if(isNaN(goodQuantityInt)){
                goodQuantityInt=0;
            }
            if(isNaN(goodsWeightInt)){
                goodsWeightInt=0;
            }
            totalgoodQuantity+=goodQuantityInt;
            totalgoodsWeightNew+=goodsWeightInt;
        };
        $('#goodsQuantity').val(totalgoodQuantity);
        totalgoodsWeightNew=parseFloat(totalgoodsWeightNew).toFixed(3)
//		           var dataStr = totalgoodsWeight+'';//先转成字符串
//		           var strs = dataStr.split(".");//切割
//		           var totalgoodsWeightNew = '';
//		           if(strs.length>1){//说明有小数位
//		        	   var str = strs[1];//取小数点后面的字符串
//		        	   if(str.length>3){//说明有精度问题
//		        		   var len = str.indexOf("0");
//		        		   var strNew = str.substr(0,len);//去除后面的0
//		        		    totalgoodsWeightNew = strs[0]+"."+strNew;
//		        	   }else{
//		        		   totalgoodsWeightNew = totalgoodsWeight;
//		        	   }
//
//
//		           }else{
//		        	   totalgoodsWeightNew = totalgoodsWeight;
//		           }
//
        $('#goodsWeight').val(totalgoodsWeightNew);
        layer.open({
            type:1,
            shadeClose:false,
            area:['520px','200px'],
            title:"提运单汇总计算",
            shade:0.5,
            scrollbar:false,
            btnAlign: 'c',//居中
            end:function(index){

            },

            content:$("#numInfoAddContent")
        });
    }else{
        showLayerWarnMsg("没有需要汇总的记录");
    }


}



//function refreshChangeResionInfo(){
//	$('#changeResionInfoTalbe').bootstrapTable("refresh");
//	$("#chgCodeName").val("");
//	$("#chgCode").val("");
//	$("#chgSeqNo").val("");
//}



/**
 *   超链接    商品详细信息查看方法
 */
function lookGoodsInfo(data,element){
    clearGoodsInfo();//先清空
    if(typeof data == 'number'){//1点击链接查看入口
        dataTemp = $('#commodityInformationTalbe').bootstrapTable('getData')[data];
        if(dataTemp){
            $('#mft_goods_info_form').setForm(dataTemp);

//			var customsTransitCode = $('#customsTransitCode').val();
//			var goodsCustomsStatCode = $("#goodsCustomsStatCode").val();
//			if(pageType=='main'){
//				if(goodsCustomsStatCode=='RD09' || goodsCustomsStatCode=='RD16'){
//					$("#customsTransit").removeClass();
//					$("#customsTransit").addClass("form-control non-empty");
//					$('#customsTransit').attr('readonly',false);
//				}else{
//					if(isNotNull(customsTransitCode)){
//						$("#customsTransit").removeClass();
//						$("#customsTransit").addClass("form-control");
//						$('#customsTransit').attr('readonly',false);
//					}else{
//						$('#customsTransit').attr('readonly',true);
//					}
//				}
//			}
            $('#goodsSeqNo').attr('readonly', true);
            //货物商品里的如果可输可选 如果遇到参数库没有的字段 反填情况
            var undgNo = $('#undgNo').val();
            //危险品编号
            if (undgNo !== null && undgNo !== undefined && undgNo !== '') {
                $('#undgNoName').autocomp({// 显示框
                    tableName:'CUS_MFT8_DAN_GOODS',// 查询的同义词
                    hiddenId:'undgNo',// 隐藏框
                    keyValue:undgNo
                });
            }
//			if (customsTransitCode !== null && customsTransitCode !== undefined && customsTransitCode !== '') {
//				$('#customsTransit').autocomp7({// 显示框
//					tableName:'PARA_CUSTOMS_TRANSIT_TYPE',// 查询的同义词
//					hiddenId:'customsTransitCode',// 隐藏框
//					keyValue:customsTransitCode
//				});
//			}
            return;
        }else{
            showLayerWarnMsg("打开详情信息失败，请刷新重试！");
            return;
        }
    }
}





/**判断变更原因是否重复，重复返回true，否则返回false**/
function judgeIsDuplicate(target,arr){
    var flag=false;
    $.each(arr,function(index,item){
        if(target==item.amendmentSeq){
            flag=true;
        }

    });

    return flag;
}



//各种联系人
function openDetail(_title,id){
    var width=null;
    var height=null;
    if(id==="#consigneeInfoAddContent"){
        width="95%";
        height="85%";
    }else{
        width="80%";
        height="80%";
    }

    layer.open({
        type: 1,
        title: _title,
        shadeClose: false,
        shade: 0.2,
        maxmin: true, //开启最大化最小化按钮
        resize:true,
        btn:['关闭'],
        btn1:function(index, layero){
            /*layer.alert('保存成功！', {
                icon: 1,
                title: '提示'
            });*/
            layer.close(index);
        },

        btnAlign: 'c',
        area: [width,height],
        end:function(index){
            //根据当前弹出层HTML页面id判断下次选择哪个按钮聚焦
            switch(id){
                case "#consigneeInfoAddContent":
                    $("#consigorInfo").focus();
                    break;
                case "#consignorInfoAddContent":
                    $("#notifyInfo").focus();
                    break;
                case "#notifyInfoAddContent":
                    $("#undgInfo").focus();
                    break;
                default:
                    $("#goodsPackNum").focus();
            }

        },
        content: $(id)
    });
}

/*############################## 舱单变更对象获取相关方法   #######################*/
//运输方式代码默认3
const transportTypeCode="3";
/*组装报文体*/
function getDeclaration(){
    var consignmentInfoList=_GConsignmentTablInfo();
    //consignment数组
    var consignmentArr=[];
    //变更原因数组
    var chgArr=getChgCode();
    //商品项信息
    var consignmentList=_GConsignmentIs();
    $.each(consignmentInfoList, function(index,item) {
        var consignment={
            "grossVolumeMeasure":{
                "value": item.cube,
                "unitCode": "MTQ"
            },
            "totalPackageQuantity": {
                "unitCode": item.goodsPackTypeCode,//包装种类
                "value": item.packNum
            },
            "valueAmount": {
                "currencyID": item.currencyTypeCode,
                "value": item.goodsValue
            },
            //收货人信息
            "consignee": item.consigneeInfo,
            //商品项信息对象
            "consignmentItem":consignmentList,
            //运费支付方法
            "freight":{
                'paymentMethodCode':item.paymentTypeCode
            },
            //货物总毛重
            "governmentAgencyGoodsItem":{
                "goodsMeasure":{
                    "grossMassMeasure":{
                        "unitCode":"KGM",
                        "value":item.grossWt
                    }
                }
            },
            //通知人信息
            "notifyParty":item.notifyInfo,
            //提运单其他部分信息
            "transportContractDocument":{
                "conditionCode": item.conditionCode,
                "id": item.billNo,
                "amendment":{"changeReasonCode": chgArr},
                "consolidator": { "id": item.consolidatorId },//拼箱人代码
                "deconsolidator": { "id": "" }
            },
            //危险品联系人信息
            "undgcontact":item.undgInfo
        };
        consignmentArr.push(consignment);

    });

    var baseData=$("#org_mtf_m_head_form").serializeJson();
    var declaration={
        "declarationOfficeID": baseData.customsCode,//customMaster
        "id": baseData.voyageNo,
        "additionalInformation": { "content": baseData.additionalInformation },
        "borderTransportMeans": { "typeCode": transportTypeCode },
        "consignment":consignmentArr,
        "representativePerson": { "name": baseData.msgRepName }
    }

    return declaration;
}

//中间提运单表格已选择行数据
function _GConsignmentTablInfo(){
    var selects = $("#billOfLadingInformationTalbe").bootstrapTable('getSelections');
    if (selects.length == 0) {
        layer.confirm('请勾选需要申报的提运单', {icon: 1, title:'提示'}, function(index){ //3提示图标
            layer.close(index);
        });
        return;
    }else{
        //获取所包含的所有值
        return selects;
    }
}

var communicationArray=[];
//收货人取值
function _GConsignee(){
    //收货具体联系人
    var contact={"name":"","communication":""};
    //收货人
    var consignee={"id":"","name":"","communication":"","contact":contact};

    var upFormJSON=$("#consignee_info_form").serializeJson();
    var consigneeInfoTalbeJSON=$("#consigneeInfoTalbe").bootstrapTable("getData");
    var dowmFormJSON=$("#consigneeContact_info_form").serializeJson();
    var consigneeContactInfoTalbeJSON=$("#consigneeContactInfoTalbe").bootstrapTable("getData");
    //进行属性赋值
    consignee.id=upFormJSON.consigneeId;
    consignee.name=upFormJSON.consigneeName;
    communicationArray=[];
    $.each(consigneeInfoTalbeJSON, function(index,item) {
        //联系方式
        var communication=new Object();
        communication.id=item.communicationNo;
        communication.typeID=item.communicationType;
        communicationArray.push(communication);
    })
    consignee.communication=communicationArray;
    consignee.contact.name=dowmFormJSON.consigneeContactName;
    communicationArray=[];
    $.each(consigneeContactInfoTalbeJSON, function(index,item) {
        //联系方式
        var communication=new Object();
        communication.id=item.communicationNo;
        communication.typeID=item.communicationTypej;
        communicationArray.push(communication);
    })
    consignee.contact.communication=communicationArray;

    return consignee;
}



//发货人取值
function _GConsignor(){
    var consignor={"id":"","name":"","communication":""};
    var formJson=$("#consignor_info_form").serializeJson();
    var tableJson=$("#consignoInfoTalbe").bootstrapTable("getData");
    consignor.id=formJson.consignorId;
    consignor.name=formJson.consignorName;
    communicationArray=[];
    $.each(tableJson, function(index,item) {
        //联系方式
        var communication=new Object();
        communication.id=item.communicationNo;
        communication.typeID=item.communicationTypef;
        communicationArray.push(communication);
    })
    consignor.communication=communicationArray;
    return consignor;
}

//通知人信息取值
function _GNotifyInfo(){
    var notifyParty={"id":"","name":"","address":{"line":""},"communication":""};
    var formJson=$("#notify_info_form").serializeJson();
    var tableJson=$("#notifyInfoTalbe").bootstrapTable("getData");
    notifyParty.id=formJson.notifyId;
    notifyParty.name=formJson.notifyName;
    notifyParty.address.line=formJson.notifyAddr;
    communicationArray=[];
    $.each(tableJson, function(index,item) {
        //联系方式
        var communication=new Object();
        communication.id=item.communicationNo;
        communication.typeID=item.communicationTypet;
        communicationArray.push(communication);
    })
    notifyParty.communication=communicationArray;
    return notifyParty;
}

//危险品联系人信息取值
function _GUndgInfo(){
    var undgContact={"name":"","communication":""};
    var formJson=$("#undg_info_form").serializeJson();
    var tableJson=$("#undgInfoTalbe").bootstrapTable("getData");
    undgContact.name=formJson.undgContactName;
    communicationArray=[];
    $.each(tableJson, function(index,item) {
        //联系方式
        var communication=new Object();
        communication.id=item.communicationNo;
        communication.typeID=item.communicationTypew;
        communicationArray.push(communication);
    })
    undgContact.communication=communicationArray;
    return undgContact;
}

//商品项数组
function _GConsignmentIs(){
    var consignmentItems =new Array();
    var consignmentIs=$("#commodityInformationTalbe").bootstrapTable("getData");
    for(var i=0;i<consignmentIs.length;i++){
        var consignmentI = {
            "sequenceNumeric": consignmentIs[i].goodsSeqNo,
            "commodity": {
                "hscode": consignmentIs[i].HSCode,//HS编码20181022 maqingsong
                "cargoDescription": consignmentIs[i].goodsBriefDesc,
                "description": consignmentIs[i].goodsDetailDesc,
                "classification": { "id": consignmentIs[i].undgNo }
            },
            "goodsMeasure": {
                "grossMassMeasure": {
                    "unitCode": "KGM",
                    "value": consignmentIs[i].goodsGrossWt
                }
            },
            "packaging": {
                "quantityQuantity": {
                    "unitCode": consignmentIs[i].goodsPackTypeCode_sp,
                    "value": consignmentIs[i].goodsPackNum
                }
            }
        };

        consignmentItems.push(consignmentI);
    }

    return consignmentItems;

}

//获取更改原因代码数组
function getChgCode(){
    var chgCodeNames =new Array();
    var chgCodes=$("#chgInfoTalbe").bootstrapTable("getData");
    for(var i=0;i<chgCodes.length;i++){
        var chgCode = chgCodes[i].chgCode;
        chgCodeNames.push(chgCode);
    }
    return chgCodeNames;
}
/*提运单表格数据清空*/
function clearBillFormData(){
    $("#org_bill_info")[0].reset();
    clearArea("changeAddContent","chgInfoTalbe");
    clearArea("consigneeInfoAddContent","consigneeInfoTalbe");
    $("#consigneeContactInfoTalbe").bootstrapTable("removeAll");
    clearArea("consignorInfoAddContent","consignoInfoTalbe");
    clearArea("notifyInfoAddContent","notifyInfoTalbe");
    clearArea("undgInfoAddContent","undgInfoTalbe");
    //1205 谢霖志 新增变更无纸化需求
    $("#reason").val("");
    $("#phone").val("");
    $("#contact").val("");
    //1205
    //商品项input清空
    clearGoodsInfo();
    $("#commodityInformationTalbe").bootstrapTable("removeAll");
    //集装箱清空
    refreshContainerInfo();
    $("#containerInformationTalbe").bootstrapTable("removeAll");
    $("#org_bill_info").find("input").each(function(){//清提运单的隐藏域，
        $(this).val("");
    });
}
function clearArea(_areaId,_tableId){
    $("#"+_areaId+" input").each(function(){
        $(this).val("")
    });
    $("#"+_tableId).bootstrapTable("removeAll");
}

function getCompanyInfo(code){
    code = $('#customMaster').val();
    if(code.length<1){
        code='';
    }
//	var unitcode = $('#unitCode').val();//用于判断组织机构代码是否需要重新反填 若存在则不反填
    var msgRepName = $('#msgRepName').val();//用于判断舱单传输人名称是否需要反填 若存在 则不反填
    //企业信息获取
    const companyInfoUrl=BasePath+"/commonQuery/getCompanyInfo";
    $.ajax({
        type : "POST",
        url : companyInfoUrl,
        data : JSON.stringify({"codeCHG":code}),
        contentType : "application/json;charset=utf-8",
        dataType : "json",
        success : function(json) {
            if(isNotEmpty(json)){
                $("#unitCode").val(json.unitCode);
                $("#customMaster").val(json.customCode);
                if(isNotEmpty(json.customCode)){
                    $('#customMasterName').autocomp({// 隐藏框
                        tableName:'CUS_CUSTOMS',// （备案机关？申报企业关区？）
                        hiddenId:'customMaster',// 显示框
                        keyValue:json.customCode
                    });
                }
                if(!isNotNull(msgRepName)){
                    $("#msgRepName").val(json.contactName);
                }

            }

        }
    });

}
/**
 * 任何时候光标移开传输企业备案关区时触发舱单传输人查询操作（后续可能会用到）
 */
$('#customMasterName').blur(function(){//传输企业备案关区失去焦点事件
    getCompanyInfo();
});
//按enter打开按钮弹窗
/*function openButtons(){
	var billButtons = [];
	billButtons.push(
			'chgCodeAddBtn', 'consigneeInfo', 'undgInfo',
			'consigorInfo', 'notifyInfo'
			);
	$("#org_bill_info button").each(function() {
		if (($.inArray($(this)[0].id, billButtons) >= 0)) {

			$(this).keydown(function(e){
				e.stopPropagation();
				if(e.keyCode==13){
					 $(this).click();
				}
			});

		}
	});

}*/

/**
 * 提运单信息更新方法（回车触发）
 */
var updateIndex = -1;
function updateBillInfoFunc(data){

    var dataBillInfo = getAllBillInfos();
    dataBillInfo.state=false;
    dataBillInfo.index=billIndex;
//    var goodsCustomsStatCode = dataBillInfo.goodsCustomsStatCode==null?"":dataBillInfo.goodsCustomsStatCode;
//	var consignmentItems = dataBillInfo.consignmentItems==null?"":dataBillInfo.consignmentItems;
//	for(var i=0;i<consignmentItems.length;i++){
//		var customsTransitCode=""
//		if(isNotNull(consignmentItems[i].customsTransitCode)){
//			customsTransitCode = consignmentItems[i].customsTransitCode
//		}
//		if(goodsCustomsStatCode=="RD09" || goodsCustomsStatCode=="RD16"){
//			if(!isNotNull(customsTransitCode)){
//				showLayerAlert("转关类型必填");
//				return;
//			}
//		}else{
//			if(isNotNull(customsTransitCode)){
//				showLayerAlert("转关类型必不填");
//				return
//			}
//		}
//	}

    var billTable=$("#billOfLadingInformationTalbe").bootstrapTable("getData");
    $('#billOfLadingInformationTalbe').bootstrapTable('updateRow', {
        index: updateIndex,
        row: dataBillInfo
    });
}

/**
 * 更新集装箱方法
 */
function updateContainerFunc(data){

    var dataTemp = $("#mft_bill_container_form").serializeJson();
    dataTemp.state=false;
    dataTemp.index=contaIndex;
    //判断有没有列表，若没有新增一条
    var contaTable=$("#containerInformationTalbe").bootstrapTable("getData");
    $('#containerInformationTalbe').bootstrapTable('updateRow', {
        index: updateContainerIndex,
        row: dataTemp
    });


    //只有一条的情况
//		if(billTable.length==1){
//			$('#containerInformationTalbe').bootstrapTable('updateRow', {
//		        index: 0,
//		        row: dataTemp
//		   });
//		}
}

/**
 * 商品信息更新方法
 */
function updateGoodsFunc(){
    var dataTemp = $("#mft_goods_info_form").serializeJson();
    dataTemp.state=false;
    dataTemp.index=commodityIndex;
    dataTemp.goodsSeqNo = dataTemp.index;
    var goodTable=$("#commodityInformationTalbe").bootstrapTable("getData");
    $('#commodityInformationTalbe').bootstrapTable('updateRow', {
        index: updateGoodsIndex,
        row: dataTemp
    });
}


/*非空判断*/
function isNotEmpty(_val){
    if(_val!=null && _val!='' && _val!=undefined){
        return true;
    }
    return false;
}

function getKey(_e){
    var e = _e || window.event;
    var key = e.keyCode || e.which || e.charCode;
    return key;
}
/*校验表头是否为空*/
function headInfoNotNull(){
    var headData=$("#org_mtf_m_head_form").serializeJson();
    if(!isNotEmpty(headData.voyageNo)){
        showLayerWarnMsg("货物运输批次号不可为空！");
        return true;
    }
    if(!isNotEmpty(headData.customsCodeName)){
        showLayerWarnMsg("进出境口岸海关代码不可为空！");
        return true;
    }
    if(!isNotEmpty(headData.loadingDate)){
        showLayerWarnMsg("货物装载时间不可为空！");
        return true;
    }
    if(!isNotEmpty(headData.loadingLocationCode)){
        showLayerWarnMsg("装货地代码不可为空！");
        return true;
    }
    if(!isNotEmpty(headData.customMasterName)){
        showLayerWarnMsg("传输企业备案关区不可为空！");
        return true;
    }
    if(!isNotEmpty(headData.msgRepName)){
        showLayerWarnMsg(" 舱单传输人名称不可为空！");
        return true;
    }
}
/*******************************************弹窗小列表回显***************************************************/
/**
 * @Method description 预配舱单 途径国家信息新增或更新方法
 * @author 马青松 2018/5/18
 * @description 新增或更新一条国家信息
 */

function addOrUpdateCountry(){
    if(countryFlag){//当更新标记为true时，执行更新方法
        updateCountryInfo();//途径国家更新方法
        countryFlag = false;//更新完毕后重置更新标记
    }else{
        addCountryInfo();//新增国家信息
    }
    refrehCountryInfo();//刷新国家信息input框
}
/**
 * @Method description 预配舱单 途径国家信息新增方法
 * @author 马青松 2018/5/18
 * @description 新增一条国家信息
 */
function  addCountryInfo(){
    //判断录入条数
    var countryInfoTalbes=$("#countryInfoTalbe").bootstrapTable("getData");//获取列表上的国家信息
    if(countryInfoTalbes.length>=99){//判断国家信息列表数据长度是否大于等于99条（最多只能新增99条国家信息）
        showLayerWarnMsg('该信息最多只能录入99条！');
        return;
    };

    var routingContryIdTextCode = $("#routingContryIdTextCode").val();//获取国家信息隐藏框的值
    var routingContryId = $("#routingContryIdText").val();//获取国家信息显示框的值
    if(routingContryId.length>0){
        var data = {
            "state":false,
            "index":countryIndex,
            "routingContryIdText":routingContryId,
            "routingContryIdTextCode":routingContryIdTextCode
        }
        $('#countryInfoTalbe').bootstrapTable('insertRow', {//新增一条国家信息
            index: countryIndex,
            row: data
        });
        countryIndex++;

    }else{
        showLayerWarnMsg("国家代码不能为空！");
    }

};
/**
 * 途径国家代码  更新事件
 */

function  updateCountryInfo(){
    //判断录入条数
    var countryInfoTalbes=$("#countryInfoTalbe").bootstrapTable("getData");
    if(countryInfoTalbes.length>=99){
        showLayerWarnMsg('该信息最多只能录入99条！');
        return;
    };

    var routingContryIdTextCode = $("#routingContryIdTextCode").val();
    var routingContryId = $("#routingContryIdText").val();
    if(routingContryId.length>0){
        var data = {
            "state":false,
            "index":countryIndex,
            "routingContryIdText":routingContryId,
            "routingContryIdTextCode":routingContryIdTextCode
        }
        $('#countryInfoTalbe').bootstrapTable('updateRow', {
            index: updateCountryIndex,
            row: data
        });
        refrehCountryInfo();
    }else{
        showLayerWarnMsg("国家代码不能为空！");
    }

};
/**
 * @Method description 预配舱单 途径国家信息回显方法
 * @author 马青松 2018/5/18
 * @description 选中某行国家信息回显到表单上
 */
function openCountryTableInfo(data){
    if(typeof data == 'number'){
        var consigneeForm = $('#countryInfoTalbe').bootstrapTable('getData')[data];//选中某行国家信息
        $('#routingContryIdText').val(consigneeForm.routingContryIdText);//input回显

    }
}
/**
 * @Method description 预配舱单 途径国家信息删除方法
 * @author 马青松 2018/5/18
 * @description 删除一条国家信息
 */
function delCountryInfo(){
    var selects = $('#countryInfoTalbe').bootstrapTable("getSelections");
    if(selects.length<1){
        layer.confirm('请勾选需删除的数据', {icon: 1, title:'提示'}, function(index){ //3提示图标
            layer.close(index);
        });
        return;
    }else{
        layer.confirm('是否确认删除该数据？', {icon: 7, title:'提示'}, function(index){ //3提示图标
            var listArr  = [];
            //取联系人的技术主键放入输入通过ajax 传送
            for(var a=0;a<selects.length;a++){
                var selectedIndex = selects[a].state;
                var s = [];
                s.push(selectedIndex)
                $('#countryInfoTalbe').bootstrapTable('remove',{field: 'state', values: s});
                countryIndex--;
            }

            countryFlag = false;
            layer.close(index);
            showLayerMsg('操作成功！')

        });


    }

};
/**
 * @Method description 预配舱单 途径国家信息input框刷新方法
 * @author 马青松 2018/5/18
 */
function refrehCountryInfo(){
    $("#routingContryIdTextCode").val("");
    $("#routingContryIdText").val("");
}
/**
 * @Method description 预配舱单 更改原因刷新方法
 * @author 马青松 2018/5/18
 */
function refrehChgInfo(){
    $("#amendmentSeq").val("");
    $("#chgCodeText").val("");


}
/**
 * @Method description 预配舱单 更改原因新增或更新方法
 * @author 马青松 2018/5/18
 * @description 新增或更新一条变更原因信息
 */

function addOrUpdateChg(){
    if(chgFlag){//更新标记为true时执行更新方法
        updateChgInfo();//变更原因更新方法
        chgFlag = false;//更新方法执行完后重置更新标记
    }else{
        addChgInfo();//变更原因新增方法
    }
    refrehChgInfo();//变更原因input刷新方法
}
/**
 * @Method description 预配舱单 更改原因新增方法
 * @author 马青松 2018/5/18
 * @description 新增一条变更原因信息
 */
function  addChgInfo(){
    //判断录入条数
    var chgInfoTalbes=$("#chgInfoTalbe").bootstrapTable("getData");//获取表单数据
    if(chgInfoTalbes.length>=3){
        showLayerWarnMsg('该信息最多只能录入3条！');
        return;
    };

    var amendmentSeq = $("#amendmentSeq").val();
    var chgCodeText = $("#chgCodeText").val();
    for(var i=0;i<chgInfoTalbes.length;i++){
        if(amendmentSeq==chgInfoTalbes[i].amendmentSeq){
            showLayerWarnMsg('变更原因不能重复！');
            return;
        }
    }
    if(chgCodeText.length>0){
        var data = {
            "state":false,
            "index":chgIndex,
            "chgCodeText":chgCodeText,
            "amendmentSeq":amendmentSeq
        }

        $('#chgInfoTalbe').bootstrapTable('insertRow', {//新增一条变更原因
            index: chgIndex,
            row: data
        });
        chgIndex++;

    }else{
        showLayerWarnMsg("变更原因不能为空！");
    }

};
/**
 * @Method description 预配舱单 更改原因更新方法
 * @author 马青松 2018/5/18
 * @description 更新一条变更原因信息
 */
function  updateChgInfo(){



    var amendmentSeq = $("#amendmentSeq").val();
    var chgCodeText = $("#chgCodeText").val();
    var chgInfoTalbes=$("#chgInfoTalbe").bootstrapTable("getData");//获取表单数据
    for(var i=0;i<chgInfoTalbes.length;i++){
        if(amendmentSeq==chgInfoTalbes[i].amendmentSeq){
            showLayerWarnMsg('变更原因不能重复！');
            return;
        }
    }
    if(chgCodeText.length>0){
        var data = {
            "state":false,
            "index":chgIndex,
            "chgCodeText":chgCodeText,
            "amendmentSeq":amendmentSeq
        };

        $('#chgInfoTalbe').bootstrapTable('updateRow', {
            index: updateChgIndex,
            row: data
        });
        refrehChgInfo();
    }else{
        showLayerWarnMsg("变更原因不能为空！");
    }

};
/**
 * @Method description 预配舱单 更改原因表单回显方法
 * @author 马青松 2018/5/18
 * @description 回显列表选中的某条数据
 */
function openChgTableInfo(data){
    if(typeof data == 'number'){
        var consigneeForm = $('#chgInfoTalbe').bootstrapTable('getData')[data];//获取列表数据
        $('#chgCodeText').val(consigneeForm.chgCodeText);//input回显

    }
}
/**
 * @Method description 预配舱单 更改原因删除方法
 * @author 马青松 2018/5/18
 * @description 删除一条变更原因信息
 */
function delChgInfo(){
    var selects = $('#chgInfoTalbe').bootstrapTable("getSelections");
    if(selects.length<1){
        layer.confirm('请勾选需删除的数据', {icon: 7, title:'提示'}, function(index){ //3提示图标
            layer.close(index);
        });
        return;
    }else{
        layer.confirm('是否确认删除该数据？', {icon: 7, title:'提示'}, function(index){ //3提示图标
            var listArr  = [];
            //取联系人的技术主键放入输入通过ajax 传送
            for(var a=0;a<selects.length;a++){
                var selectedIndex = selects[a].state;
                var s = [];
                s.push(selectedIndex)
                $('#chgInfoTalbe').bootstrapTable('remove',{field: 'state', values: s});
                chgIndex--;
            }
            refrehChgInfo();
            layer.close(index);
            showLayerMsg('操作成功！')
            chgFlag = false;
        });
    }
};
/**
 * @Method description 预配舱单 收货人新增或更新方法
 * @author 马青松 2018/5/18
 * @description 根据标记执行更新或新增方法
 */

function addOrUpdateConsignee(){
    if(consigneeFlag){//更新标记为true时执行更新方法
        updateConsignee();//更新方法
        consigneeFlag = false;//更新完毕后重置更新标记
    }else{
        addConsignee();//新增方法
    }
    clearContactInfo();	//清空收货人表单
}
/**
 * @Method description 预配舱单 收货人新增方法
 * @author 马青松 2018/5/18
 */
function addConsignee(){
    var communicationConsignee =new Array();
    //判断录入条数
    var communications=$("#consigneeInfoTalbe").bootstrapTable("getData");//获取列表所有数据
    if(communications.length>=3){//所有联系人联系方式最多录入三条
        showLayerWarnMsg('该信息最多只能录入3条！');
        return;
    }
    var jsonData = $("#consignee_info_form").serializeJson();//表单数据序列化
    jsonData.state = false;
    if(jsonData.consigneeName.length>0){//判断收货人名称是否存在
        if (jsonData.communicationNo.length>0) {//判断联系号码是否存在
            if (jsonData.communicationTypeText.length>0) { //判断通讯方式类别是否存在
                jsonData.index = consigneeIndex;
                $('#consigneeInfoTalbe').bootstrapTable('insertRow', {//都存在数据从可执行新增方法
                    index:consigneeIndex,
                    row: jsonData
                });
                consigneeIndex++;
                clearContactInfo();//数据添加完成清空表单
            }else{
                showLayerWarnMsg("通讯方式类别不能为空！");
            }
        }else{
            showLayerWarnMsg("联系号码不能为空！");
        };
    }else{
        showLayerWarnMsg("收货人名称不能为空！");
    }
}
/**
 * @Method description 预配舱单 收货人更新方法
 * @author 马青松 2018/5/18
 */
function updateConsignee(){
    var communicationConsignee =new Array();

    var jsonData = $("#consignee_info_form").serializeJson();//获取表单对象
    jsonData.state = false;
    if(jsonData.consigneeName.length>0){//判断收货人名称是否存在
        if (jsonData.communicationNo.length>0) {//判断联系号码是否存在
            if (jsonData.communicationTypeText.length>0) { //判断通讯方式类别是否存在
                jsonData.index = consigneeIndex;
                $('#consigneeInfoTalbe').bootstrapTable('updateRow', {//执行更新操作
                    index:updateConsigneeIndex,
                    row: jsonData
                });
                clearContactInfo();
            }else{
                showLayerWarnMsg("通讯方式类别不能为空！");
            }
        }else{
            showLayerWarnMsg("联系号码不能为空！");
        };
    }else{
        showLayerWarnMsg("收货人名称不能为空！");
    }
}
/**
 * @Method description 预配舱单 列表数据回显
 * @author 马青松 2018/5/18
 * @param 被选中行的行号（行所在列表的位置）
 */
function openConsigneeInfo(data) {
    if(typeof data == 'number'){
        var consigneeForm = $('#consigneeInfoTalbe').bootstrapTable('getData')[data];
        $('#consignee_info_form').setForm(consigneeForm);//表单回显
        if(isNotNull(consigneeForm.communicationType)){
            $('#communicationTypeText').autocomp({// 显示框
                tableName:'CUS_MFT8_COMMUNI_TYPE',// 查询的同义词
                hiddenId:'communicationType',// 隐藏框
                keyValue:consigneeForm.communicationType//hidden值
            });
        }
//		if(data.consignmentItems[i].customsTransitCode !==null && data.consignmentItems[i].customsTransitCode !== undefined && data.consignmentItems[i].customsTransitCode !=''){
//			$('#customsTransit').autocomp7({// 显示框
//				tableName:'PARA_CUSTOMS_TRANSIT_TYPE',// 查询的同义词
//				hiddenId:'customsTransitCode',// 隐藏框
//				keyValue:data.consignmentItems[i].customsTransitCode
//			});
//		}
    }
}
/**
 * @Method description 预配舱单 收货人具体联系人新增或更新方法
 * @author 马青松 2018/5/18
 * @description 根据标记执行新增或更新操作
 */

function addOrUpdateConsigneeContact(){
    if(updateconsigneeContactIndexFlag){//更新标记为true时执行更新操作
        updateConsigneeContact();//更新方法
        updateconsigneeContactIndexFlag = false;//更新完成后重置更新标记
    }else{
        addconsigneeContact();//新增方法
    }
}
/**
 * @Method description 预配舱单 收货人具体联系人新增方法
 * @author 马青松 2018/5/18
 * @description 在列表上新增一条数据
 */
function addconsigneeContact(){
    //判断收货人名称是否为空，若为空提示，不为空继续
    var consignee = $("#consigneeName").val();
    if(!isNotNull(consignee)){
        showLayerWarnMsg('收货人名称不可为空！');
        return;
    }
    //判断录入条数
    var consigneeCommunications=$("#consigneeContactInfoTalbe").bootstrapTable("getData");
    if(consigneeCommunications.length>=3){
        showLayerWarnMsg('该信息最多只能录入3条！');
        return;
    };
    var jsonData = $("#consigneeContact_info_form").serializeJson();//获取表单数据
    jsonData.state = false;
    if(jsonData.consigneeContactName.length>0){
        if (jsonData.communicationNo.length>0) {
            if (jsonData.communicationTypeTextj.length>0) {
                jsonData.index = consigneeContactIndex;
                $('#consigneeContactInfoTalbe').bootstrapTable('insertRow', {//执行新增操作
                    index:consigneeContactIndex,
                    row: jsonData
                });
                consigneeContactIndex++;
                clearConsigneeContactInfo();
            }else{
                showLayerWarnMsg("通讯方式类别不能为空！");
            }
        }else{
            showLayerWarnMsg("联系号码不能为空！");
        };
    }else{
        showLayerWarnMsg("具体联系人名称不能为空！");
    }
}
/**
 * @Method description 预配舱单 收货人具体联系人更新方法
 * @author 马青松 2018/5/18
 * @param  updateconsigneeContactIndex 指定要更新行的位置
 * @description 更新指定行
 */
function updateConsigneeContact(){
    //判断收货人名称是否为空，若为空提示，不为空继续
    var consignee = $("#consigneeName").val();
    if(!isNotNull(consignee)){
        showLayerWarnMsg('收货人名称不可为空！');
        return;
    }


    var jsonData = $("#consigneeContact_info_form").serializeJson();//获取表单数据
    jsonData.state = false;
    if(jsonData.consigneeContactName.length>0){//判断表单数据 执行更新操作
        if (jsonData.communicationNo.length>0) {
            if (jsonData.communicationTypeTextj.length>0) {
                jsonData.index = consigneeContactIndex;
                $('#consigneeContactInfoTalbe').bootstrapTable('updateRow', {
                    index:updateconsigneeContactIndex,
                    row: jsonData
                });
                clearConsigneeContactInfo();
            }else{
                showLayerWarnMsg("通讯方式类别不能为空！");
            }
        }else{
            showLayerWarnMsg("联系号码不能为空！");
        };
    }else{
        showLayerWarnMsg("具体联系人名称不能为空！");
    }
}
/**
 * @Method description 预配舱单 收货人具体联系人列表回显方法
 * @author 马青松 2018/5/18
 * @param  data 指定要回显行的位置
 * @description 表单回显列表数据
 */
function openConsigneeContactIndexInfo(data){
    if(typeof data == 'number'){
        var consigneeForm = $('#consigneeContactInfoTalbe').bootstrapTable('getData')[data];//指定行的数据
        $('#consigneeContact_info_form').setForm(consigneeForm);//表单回显
        $('#communicationTypeTextj').autocomp({// 显示框
            tableName:'CUS_MFT8_COMMUNI_TYPE',// 查询的同义词
            hiddenId:'communicationTypej',// 隐藏框
            keyValue:consigneeForm.communicationTypej//hidden值
        });
    }
}
/**
 * @Method description 预配舱单 发货人新增或更新方法
 * @author 马青松 2018/5/18
 * @description 根据更新标记判断是更新还是新增
 */

function addOrUpdateConsignor(){
    if(consignorFlag){//标记为true时执行更新操作
        updateConsignor();//更新方法
        consignorFlag = false;//更新完成后重置标记
    }else{
        addconsignor();//新增方法
    }
}
/**
 * @Method description 预配舱单 发货人新增方法
 * @author 马青松 2018/5/18
 * @description 新增一行数据
 */
function addconsignor(){
    //判断录入条数
    var consignoCommunications=$("#consignoInfoTalbe").bootstrapTable("getData");
    if(consignoCommunications.length>=3){
        showLayerWarnMsg('该信息最多只能录入3条！');
        return;
    };

    var jsonData = $("#consignor_info_form").serializeJson();//获取表单数据
    jsonData.state = false;
    if(jsonData.consignorName.length>0){//判断数据是否存在，执行新增方法
        if (jsonData.communicationNo.length>0) {
            if (jsonData.communicationTypeTextf.length>0) {
                jsonData.index = consignorIndex;
                $('#consignoInfoTalbe').bootstrapTable('insertRow', {
                    index:consignorIndex,
                    row: jsonData
                });
                consignorIndex++;
                clearconsignorInfo();//新增完毕后清空表单
            }else{
                showLayerWarnMsg("通讯方式类别不能为空！");
            }
        }else{
            showLayerWarnMsg("联系号码不能为空！");
        };
    }else{
        showLayerWarnMsg("发货人名称不能为空！");
    }
}
/**
 * @Method description 预配舱单 发货人更新方法
 * @author 马青松 2018/5/18
 * @param  updateConsignorIndex 指定要更新行的位置
 * @description 更新指定行
 */
function updateConsignor(){
    //判断录入条数
    var consignoCommunications=$("#consignoInfoTalbe").bootstrapTable("getData");


    var jsonData = $("#consignor_info_form").serializeJson();//获取表单数据
    jsonData.state = false;
    if(jsonData.consignorName.length>0){//判断数据是否存在
        if (jsonData.communicationNo.length>0) {
            if (jsonData.communicationTypeTextf.length>0) {
                jsonData.index = consignorIndex;
                $('#consignoInfoTalbe').bootstrapTable('updateRow', {//执行更新方法
                    index:updateConsignorIndex,
                    row: jsonData
                });
                clearconsignorInfo();
            }else{
                showLayerWarnMsg("通讯方式类别不能为空！");
            }
        }else{
            showLayerWarnMsg("联系号码不能为空！");
        };
    }else{
        showLayerWarnMsg("发货人名称不能为空！");
    }
}
/**
 * @Method description 预配舱单 发货人列表回显
 * @author 马青松 2018/5/18
 * @param  data 指定要回显行的位置
 * @description 将指定行的数据回显到表单
 */
function openConsignorInfo(data){
    if(typeof data == 'number'){
        var consigneeForm = $('#consignoInfoTalbe').bootstrapTable('getData')[data];//获取指定行的数据
        $('#consignor_info_form').setForm(consigneeForm);//表单回显
        $('#communicationTypeTextf').autocomp({// 显示框
            tableName:'CUS_MFT8_COMMUNI_TYPE',// 查询的同义词
            hiddenId:'communicationTypef',// 隐藏框
            keyValue:consigneeForm.communicationTypef//hidden值
        });
    }
}
/**
 * @Method description 预配舱单 通知人更新或新增方法
 * @author 马青松 2018/5/18
 * @param  notifyFlag 更新标记
 * @description 根据标记的状态执行更新或新增方法
 */

function addOrUpdateNotify(){
    if(notifyFlag){//更新标记为true时 执行更新方法
        updateNotifyPerson();//更新方法
        notifyFlag = false;//更新完成后重置更新标记
    }else{
        addNotifyPerson();//新增方法
    }
}
/**
 * @Method description 预配舱单 通知人新增方法
 * @author 马青松 2018/5/18
 * @description 新增一条数据
 */
function addNotifyPerson(){
    //判断录入条数
    var notifyCommunications=$("#notifyInfoTalbe").bootstrapTable("getData");
    if(notifyCommunications.length>=3){
        showLayerWarnMsg('该信息最多只能录入3条！');
        return;
    };
    var jsonData = $("#notify_info_form").serializeJson();//获取表单数据
    jsonData.state = false;
    if(jsonData.notifyName.length>0){//判断数据有无，若都存在执行新增方法
        if (jsonData.communicationNo.length>0) {
            if (jsonData.communicationTypeTextt.length>0) {
                jsonData.index = notifyIndex;
                $('#notifyInfoTalbe').bootstrapTable('insertRow', {
                    index:notifyIndex,
                    row: jsonData
                });
                notifyIndex++;
                clearaddnotifyInfo();
            }else{
                showLayerWarnMsg("通讯方式类别不能为空！");
            }
        }else{
            showLayerWarnMsg("联系号码不能为空！");
        };
    }else{
        showLayerWarnMsg("通知人名称不能为空！");
    }
}
/**
 * @Method description 预配舱单 通知人更新方法
 * @author 马青松 2018/5/18
 * @parame updateNotifyIndex 需要更新行的位置
 * @description 更新一条数据
 */
function updateNotifyPerson(){
    //判断录入条数
    var notifyCommunications=$("#notifyInfoTalbe").bootstrapTable("getData");

    var jsonData = $("#notify_info_form").serializeJson();//获取表单数据
    jsonData.state = false;
    if(jsonData.notifyName.length>0){
        if (jsonData.communicationNo.length>0) {//数据是否存在判断
            if (jsonData.communicationTypeTextt.length>0) {
                jsonData.index = notifyIndex;
                $('#notifyInfoTalbe').bootstrapTable('updateRow', {//执行更新操作
                    index:updateNotifyIndex,
                    row: jsonData
                });
                clearaddnotifyInfo();
            }else{
                showLayerWarnMsg("通讯方式类别不能为空！");
            }
        }else{
            showLayerWarnMsg("联系号码不能为空！");
        };
    }else{
        showLayerWarnMsg("通知人名称不能为空！");
    }
}
/**
 * @Method description 预配舱单 通知人列表回显方法
 * @author 马青松 2018/5/18
 * @parame data 需要回显行的位置
 * @description 回显列表数据到表单
 */
function openNotifyInfo(data){
    if(typeof data == 'number'){
        var consigneeForm = $('#notifyInfoTalbe').bootstrapTable('getData')[data];//需要回显的数据
        $('#notify_info_form').setForm(consigneeForm);//表单回显
        $('#communicationTypeTextt').autocomp({// 显示框
            tableName:'CUS_MFT8_COMMUNI_TYPE',// 查询的同义词
            hiddenId:'communicationTypet',// 隐藏框
            keyValue:consigneeForm.communicationTypet//hidden值
        });
    }
}
/**
 * @Method description 预配舱单 危险品联系人新增或更新方法
 * @author 马青松 2018/5/18
 * @parame undgFlag 更新标记
 * @description 根据标记状态 执行新增或更新方法
 */

function addOrUpdateUndg(){
    if(undgFlag){//标记为true时执行更新操作
        updateUndg();//更新方法
        undgFlag = false;//更新方法执行完后重置更新标记
    }else{
        addUndg();//新增方法
    }
}
/**
 * @Method description 预配舱单 危险品联系人新增方法
 * @author 马青松 2018/5/18
 * @description 新增一条数据
 */
function addUndg(){
    //判断录入条数
    var undgCommunications=$("#undgInfoTalbe").bootstrapTable("getData");
    if(undgCommunications.length>=3){
        showLayerWarnMsg('该信息最多只能录入3条！');
        return;
    };
    var jsonData = $("#undg_info_form").serializeJson();//获取表单数据
    jsonData.state = false;
    if(jsonData.undgContactName.length>0){//判断数据是否存在
        if (jsonData.communicationNo.length>0) {
            if (jsonData.communicationTypeTextw.length>0) {
                jsonData.index = undgIndex;
                $('#undgInfoTalbe').bootstrapTable('insertRow', {//执行新增方法
                    index:undgIndex,
                    row: jsonData
                });
                undgIndex++;
                clearaddundgInfo();//新增完成清空表单
            }else{
                showLayerWarnMsg("通讯方式类别不能为空！");
            }
        }else{
            showLayerWarnMsg("联系号码不能为空！");
        };
    }else{
        showLayerWarnMsg("危险品联系人名称不能为空！");
    }
}
/**
 * @Method description 预配舱单 危险品联系人更新方法
 * @author 马青松 2018/5/18
 * @param updateUndgIndex 需要更新行的位置
 * @description 更新一条数据
 */
function updateUndg(){

    var jsonData = $("#undg_info_form").serializeJson();//获取表单数据
    jsonData.state = false;
    if(jsonData.undgContactName.length>0){//判断数据是否存在
        if (jsonData.communicationNo.length>0) {
            if (jsonData.communicationTypeTextw.length>0) {
                jsonData.index = undgIndex;
                $('#undgInfoTalbe').bootstrapTable('updateRow', {//更新数据
                    index:updateUndgIndex,
                    row: jsonData
                });
                clearaddundgInfo();//清空表单
            }else{
                showLayerWarnMsg("通讯方式类别不能为空！");
            }
        }else{
            showLayerWarnMsg("联系号码不能为空！");
        };
    }else{
        showLayerWarnMsg("危险品联系人名称不能为空！");
    }
}
/**
 * @Method description 预配舱单 危险品联系人列表回显
 * @author 马青松 2018/5/18
 * @param data 需要回显行的位置
 * @description 将列表数据回显到表单上
 */
function openUndgInfo(data){
    if(typeof data == 'number'){
        var consigneeForm = $('#undgInfoTalbe').bootstrapTable('getData')[data];//获取指定行的数据
        $('#undg_info_form').setForm(consigneeForm);//表单回显
        $('#communicationTypeTextw').autocomp({// 显示框
            tableName:'CUS_MFT8_COMMUNI_TYPE',// 查询的同义词
            hiddenId:'communicationTypew',// 隐藏框
            keyValue:consigneeForm.communicationTypew//hidden值
        });
    }
}
function isContaIdRepeat(data){
    //判断同一提运单下集装箱编号是否重复
    var consigmentTables=data;//获取所有提运单
    //var contaArrays = [];
    var flag = false;//有重复变为true
    var contaIdArray=[];
    if(consigmentTables.length>0){//抽出所有提运单的集装箱数组合并成一个大数组
        for(var i=0;i<consigmentTables.length;i++){//每一条提运单下的集装箱数组
            var contaArrays = consigmentTables[i].transportEquipments;
            var tempJson = {};
            if(isNotNull(contaArrays)&&contaArrays.length>0){
                for(var j=0;j<contaArrays.length;j++){

                    if(tempJson.hasOwnProperty(contaArrays[j].id)){//判断对象中是否包含某个key
                        showLayerWarnMsg("提运单号"+consigmentTables[i].billNo+"下集装箱号"+contaArrays[j].id+"重复");
                        flag = true;
                        break;
                    }
                    tempJson[contaArrays[j].id]=j;

                }
            }
        }
    }
    return flag;
}
//判断HS码是否必填服务
function checkHSCode(data){
    var checkFlag = false;
    var jsonVo ={
        "serviceName":"eport.superpass.roadmft.LoadListDataExangeSwitchQueryService",
        "queryLoadListDataExangeRequest":
            {
//				 "customStatusCode":"",
            "customsCode":data,
            "ieflag":"E",
            "switchType":"MN_DATA_EXCH_CHECK"
        }
    }

    $.ajax({
        type : "POST",
        url : BasePath+"/advanceManifest/checkHSCode?msgType="+ msgType,
        data : JSON.stringify(jsonVo),
        async: false,//同步方法
        contentType : "application/json;charset=utf-8",
        dataType : "json",
        success : function(json) {

            if(isNotNull(json.querySwitchResponse)&&json.querySwitchResponse.onFlag=="1"){
                checkFlag = true;
            }
        },
        complete:function(){
            layer.close();
        }
    });
    return checkFlag;
}
function resetHsCodeList(){
    $("#HSCode").removeClass("autocompleter-node");
    $("#HSCode").next().empty();
}

//无纸化变更
function  checkChangeInformation() {
    var phone = $("#phone").val();
    var contact = $("#contact").val();
    var reg = /^[\u3220-\uFA29]+$/;
    if (reg.test(contact)) {
        if(contact.length >25){
            showLayerWarnMsg("变更申请联系人姓名字段为中文，长度应小于25");
            return true;
        }
    }
    if (reg.test(phone)) {
        if(phone.length>25){
            showLayerWarnMsg("变更申请联系人电话字段为中文，长度应小于25");
            return true;
        }
    }
    return false;
}
function changeClass(){
//	$("#customsTransit").removeAttr("readonly");
    $("#transLocationId").removeAttr("readOnly");
    var goodsCustomsStatCode=$("#goodsCustomsStatCode").val()
    if(goodsCustomsStatCode=='RD09' || goodsCustomsStatCode=="RD16"){
//		$("#customsTransit").removeClass();
//		$("#customsTransit").addClass("form-control non-empty");

        $("#transLocationId").removeClass();
        $("#transLocationId").addClass("form-control non-empty");
        $("#transLocationId").focus();
    }else{
//		$("#customsTransit").removeClass();
//		$("#customsTransit").addClass("form-control");
//		$("#customsTransit").val("")
//		$("#customsTransitCode").val("")
//		$("#customsTransit").attr("readonly","readonly")

        $("#transLocationId").removeClass();
        $("#transLocationId").addClass("form-control");
        $("#transLocationId").attr("readOnly", "readOnly");
        $("#transLocationIdCode").val('');//清空隐藏框
        $("#transLocationId").val('');//清空显示框
    }
}